Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

End array map at an index?

Is it possible to only map an array up to a certain index?

For example, say I have the following:

var nums = [1, 2, 3, 4, 5];

I want to sum up the numbers in the array, but only up to the 3rd index. Is it possible to pass in an argument to Array.map() to only go up to a given index? Or is this only possible using a for loop?

like image 208
MarksCode Avatar asked Oct 29 '25 17:10

MarksCode


1 Answers

Just use slice.

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

nums.slice(0,3).map(...);
like image 147
Travis J Avatar answered Oct 31 '25 06:10

Travis J