Categories
JavaScript Answers

How to sum two arrays in single iteration with JavaScript?

Spread the love

Sometimes, we want to sum two arrays in single iteration with JavaScript.

In this article, we’ll look at how to sum two arrays in single iteration with JavaScript.

How to sum two arrays in single iteration with JavaScript?

To sum two arrays in single iteration with JavaScript, we use the array 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 function that returns the sum of num and the number in array2 at the same index as num.

An array with the sums of each entry from each array at the given index is returned.

Conclusion

To sum two arrays in single iteration with JavaScript, we use the array map method.

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 *