Sometimes, we want to sum elements at the same index in array of arrays into a single array with JavaScript.
In this article, we’ll look at how to sum elements at the same index in array of arrays into a single array with JavaScript.
How to sum elements at the same index in array of arrays into a single array with JavaScript?
To sum elements at the same index in array of arrays into a single array with JavaScript, we can use some array methods.
For instance, we write:
const arr = [
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
]
const [first] = arr
const sums = first.map((_, i) => {
return arr.map(a => a[i]).reduce((a, b) => a + b, 0)
})
console.log(sums)
We get the first nested array from arr
with destructuring and assign it to first
.
Next, we call first.map
with a callback that returns the items of each entry with the given index of each nested array.
Then we call reduce
with a callback to sum all the entries together.
Therefore, sums
is [17, 10, 19]
.
Conclusion
To sum elements at the same index in array of arrays into a single array with JavaScript, we can use some array methods.