How to add two arrays in pairs

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

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

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

This is not the same question as. I would like to add numbers and not create subarrays.

I know what you can do for(i = 0; i < array1.length; i++){array3[i] = array1[i] + array2[i]}, but I would like to know if there is any inline code that does this.

+4
source share
3 answers

Use method Array#map()

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

console.log(array3);
Hide result

ES6 arrow

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

console.log(array3);
Hide result

polyfill .

+8

.

function *addPairwise(a1, a2) {
  let i1 = a1[Symbol.iterator](), i2 = a2[Symbol.iterator](), x1, x2;

  while (1) {
    x1 = i1.next();
    x2 = i2.next();
    if (x1.done && x2.done) return;
    yield x1.done ? x2.value : x2.done ? x1.value : x1.value + x2.value;
  }
}

for...of , , , next .

, .

console.log([...addPairwise([1,2,3], [4,1,0])]);

, addPairwise,

addPairwise([1, 2, 3].values(), [4, 1, 0].values())

ES6, node v6, Chrome 51 babel.

+3

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

var array3 = add(array1, array2);
console.log(array3);

function add(arr1, arr2) {
  return arr1.map(function(value, index) {
    return value + arr2[index];
  });
}
Hide result

IE8:

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

var array3 = add(array1, array2);
console.log(array3);

function add(arr1, arr2) {
  var newArray = [];
  
  for(var i = 0; i < arr1.length; i++){
    newArray.push(arr1[i] + arr2[i]);
  }
  
  return newArray;
}
Hide result
-1
source

All Articles