Languages

JavaScript - sum two arrays in single iteration

0 points
Asked by:
Kadeem-Craig
516

How can I sum two arrays in single iteration?

I want to sum each value of an array with its corresponding value in the second array and I want to do this without looping through each individual value.

For example:

var array1 = [1, 2, 3];
var array2 = [6, 5, 4];

the result I want to get:

var sum = [7, 7, 7];
1 answer
0 points
Answered by:
Kadeem-Craig
516

You need a loop to do so but a simple solution to sum two arrays is by using map() method.

Practical example:

// ONLINE-RUNNER:browser;

var array1 = [1, 2, 3];
var array2 = [6, 5, 4];

var sum = array1.map(function(number, index) {
    return number + array2[index];
});

console.log(sum); // [ 7, 7, 7 ]

 

References

  1. Array.prototype.map() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join