Reputation: 8604
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?
Upvotes: 4
Views: 5739
Reputation: 5690
you can use slice()
function which 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(//your code);
for more information
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Upvotes: 0
Reputation: 2041
By definition, map() is called on every element in the array. See the docs for details here. So, yes, you would need to use a different solution such as a for loop.
Upvotes: 2
Reputation: 9808
you can use slice()
to get array till a specific index
nums.slice(0,3).map();
Upvotes: 1