简体   繁体   中英

How do I sum the respective elements of two arrays into another array in Javascript?

I have two arrays:

var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 5];

I want the final array to be:

var arr3 = [3, 5, 7, 9]

If possible, how could I use a callback to carry this out?

Use Array.map (see MDN )

 const arr1 = [1, 2, 3, 4]; const arr2 = [2, 3, 4, 5]; const sums = arr1.map((v, i) => v + arr2[i]); document.querySelector('#result').textContent = JSON.stringify(sums);
 <pre id="result"></pre>

Simply,

var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 5];
var arr3 = [];
var i = 0;

for (; i < arr1.length; i++) {
    arr3[i] = arr1[i] + arr2[i];
}

console.log(arr3);

DEMO

Just loop through array and sum up values

 var arr1 = [1, 2, 3, 4]; var arr2 = [2, 3, 4, 5]; var arr3 = []; for (i in arr1) { arr3[i] = arr1[i] + arr2[i]; } console.log(arr3);

You can check this,

function myFun(){ 
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 5];
var arr3 = [];
var i = 0;
if(arr1.length == arr2.length){
for (; i < arr1.length; i++) 
arr3 [i] = arr1[i] + arr2[i];
console.log(arr3 );
} else{
console.log("Both arrays length are not equal");
}
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM