To sum two arrays in single iteration with JavaScript, we use the map
method.
For instance, we write
const array1 = [1, 2, 3, 4];
const array2 = [5, 6, 7, 8];
const sum = array1.map((num, idx) => {
return num + array2[idx];
});
to call array1.map
with a callback that returns the sum of num
and item in array2
at the same idx
index.
The array with the sums is returned.