Categories
JavaScript Answers

How to sum two arrays in single iteration with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *