2

Is there a way (like we have in C# generics/linq list.take...) that can take a range of elements of an array in the argument while calling a function, without having to create a new array?

//a simple array with some elements
myArray; 
//just to show what I mean...pass the first five elemtns of array to the function
doSomethingWithArray(myArray[0,4]); 


function doSomethingWithArray(items) {
   //do stuff
}
BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
Dumbo
  • 13,555
  • 54
  • 184
  • 288

1 Answers1

4

Sounds like you might be looking for slice.

doSomethingWithArray(myArray.slice(0, 4))

Slice takes start and end parameters and returns a shallow copy of the items in the array that fall within that range. If you want to mutate the array you can consider splice.

Note that the end index is non-inclusive, i.e. myArray.slice(0,4), in the example, returns only elements in the range [0 .. 3].

Dan Prince
  • 29,491
  • 13
  • 89
  • 120