Skip to content Skip to sidebar Skip to footer

How To Add Two Arrays In Pairwise Fashion

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

Solution 1:

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.

Solution 2:

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

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

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

For IE8 support:

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

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

functionadd(arr1, arr2) {
  var newArray = [];
  
  for(var i = 0; i < arr1.length; i++){
    newArray.push(arr1[i] + arr2[i]);
  }
  
  return newArray;
}

Post a Comment for "How To Add Two Arrays In Pairwise Fashion"