MarksCode
MarksCode

Reputation: 8604

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?

Upvotes: 4

Views: 5739

Answers (4)

Shafiqul Islam
Shafiqul Islam

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

yoursweater
yoursweater

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

Dij
Dij

Reputation: 9808

you can use slice() to get array till a specific index

nums.slice(0,3).map();

Upvotes: 1

Travis J
Travis J

Reputation: 82297

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(...);

Upvotes: 17

Related Questions