Donald Duck Donald Duck - 6 months ago 20
Javascript Question

How to add two arrays in javascript

I would like to add the values of two JavaScript arrays that have the same length to get a third array so that the the first value of the third array is the sum of the first values of the two first arrays, the second value of the third array is the sum of the second values of the two first arrays, etc. For example:

var array1 = [1,2,3];
var array2 = [4,1,0];
var array3 = array1 + array2;


I would like the result of
array3
to be
[1+4, 2+1, 3+0]
=
[5,3,3]
.

This is not the same question as this. I would like to add the numbers and not make sub-arrays.

I know that there are workarounds like
for(i = 0; i < array1.length; i++){array3[i] = array1[i] + array2[i]}
but I would like to know if there is a built-in code that does this.

Answer

Use Array#map() method

var array1 = [1, 2, 3];
var array2 = [4, 1, 0];
var array3 = array1.map(function(v, i) {
  return v + array2[i];
})

console.log(array3);


For latest browser use it with ES6 arrow function

var array1 = [1, 2, 3];
var array2 = [4, 1, 0];
var array3 = array1.map((v, i) => v + array2[i])

console.log(array3);


For older browser check polyfill option of map method.