Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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 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 a built-in code that does this.

like image 640
Donald Duck Avatar asked Dec 18 '22 16:12

Donald Duck


1 Answers

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.

like image 162
Pranav C Balan Avatar answered Jan 08 '23 16:01

Pranav C Balan