codeBarer codeBarer - 4 months ago 13
Javascript Question

Is JavaScript's array map prototype a little off?

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.

Answer

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
Comments