Sergey Metlov Sergey Metlov - 2 months ago 41
Javascript Question

How to get subarray from array?

I have

var ar = [1, 2, 3, 4, 5]
and want some function
getSubarray(array, fromIndex, toIndex)
, that result of call
getSubarray(ar, 1, 3)
is new array
[2, 3, 4]
.

Answer

Take a look at Array.slice()

var ar = [1, 2, 3, 4, 5];
var ar2 = ar.slice(1, 1 + 3);

print(ar2)
>>2,3,4