3

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?

MarksCode
  • 8,074
  • 15
  • 64
  • 133
  • 2
    Why are you using map() to sum? reduce() would be better – epascarello Jul 10 '17 at 19:10
  • For something as simple as your example, `nums[0]+nums[1]+nums[2]` would be my choice. For more complicated functions and bigger arrays (and sub-arrays), you might want to come up with your own function to do the iteration with a simple `for` loop to avoid copying and unnecessary iteration. – Pointy Jul 10 '17 at 19:12
  • Sorry, I meant to say reduce :( – MarksCode Jul 10 '17 at 19:12
  • This was marked as a duplicate of a forEach question which suggests to use break (https://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break). However, `VM1292:1 Uncaught SyntaxError: Illegal break statement` will occur if that is used in map. I am voting to reopen. – Travis J Jul 10 '17 at 19:30

4 Answers4

16

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(...);
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • This is a fine way to proceed, but it should be noted that `.slice()` will create a new array and copy elements into it over the requested range. If the actual problem being solved involves a large original array and the actual range is also fairly large, this would be more expensive than using a simple `for` loop. – Pointy Jul 10 '17 at 19:13
2

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.

yoursweater
  • 1,883
  • 3
  • 19
  • 41
1

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

nums.slice(0,3).map();
Dij
  • 9,761
  • 4
  • 18
  • 35
0

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

Shafiqul Islam
  • 5,570
  • 2
  • 34
  • 43