1

I was playing around with JavaScript's array prototype map and I don't understand why I'm getting the following values:

console.log(
    [1,2,2,5,6].map(function(a,b){ 
        return a+b; 
    })
); /*This returns [ 1, 3, 4, 8, 10 ]*/

Shouldn't the above code return [1,3,4,7,11] ?

Here's another snippet which shows that elements in the array are added sequentially and are correct at least I believe so.

console.log(
    [1,2,3,4,5,6].map(function(a,b){
        return a+b;
    })
); /*[ 1, 3, 5, 7, 9, 11 ]*/

This is just a curious question more along the lines of why the first snippet of code seems.

codeBarer
  • 2,238
  • 7
  • 44
  • 75

3 Answers3

5

It's because map passes you the value as the first parameter and the index as the second. So, what you're adding is: 1 + 0, 2+1, 2+2, 5+3, etc.

Your a value is the value out of the array: 1, 2, 2, 5, 6

Your b value is actually an index, not a value out of the array: 0, 1, 2, 3, 4

Christopher Davies
  • 4,461
  • 2
  • 34
  • 33
4

Let's sum:

  [1, 2, 2, 5, 6]  // Your values
+ [0, 1, 2, 3, 4]  // Indices
-----------------
  [1, 3, 4, 8,10]  // Result
  [1, 2, 3, 4, 5, 6]  // Your values
+ [0, 1, 2, 3, 4, 5]  // Indices
--------------------
  [1, 3, 5, 7, 9,11]  // Result

The results are correct.

I think you are confusing map with reduce:

var arr = [];
[1,2,2,5,6].reduce(function(a,b){ 
  arr.push(a+b);
  return b; 
}, 0);
arr; // [1, 3, 4, 7, 11]
  [0, 1, 2, 2, 5]  // Values returned in previous iteration
+ [1, 2, 2, 5, 6]  // Your values
-----------------
  [1, 3, 4, 7,11]  // Result
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • You're correct. I was reading the documentation of reduce and I though I could sequentially add elements using map :). Thanks! – codeBarer Jul 09 '16 at 21:41
1

so the first parameter 'a' is value and the 'b' is index. so adding together it shows the corect value only. so 'a' contains [1, 2, 2, 5, 6] and 'b' contains [0, 1, 2, 3, 4]

htoniv
  • 1,658
  • 21
  • 40