Let's say that I have an array of arrays, like so:
[
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
]
How do I generate a new array that sums all of the values at each position of the inner arrays in javascript? In this case, the result would be: [17, 10, 19]. I need to be able to have a solution that works regardless of the length of the inner arrays. I think that this is possible using some combination of map and for-of, or possibly reduce, but I can't quite wrap my head around it. I've searched but can't find any examples that quite match this one.
Assuming array is static as op showned.
You can use
Array.prototype.reduce()
in combination withArray.prototype.forEach()
.Update, a shorter approach by taking a map for reducing the array.
Using Lodash 4:
For older Lodash versions and some remarks
Lodash 4 has changed the way
_.unzipWith
works, now the iteratee gets all the values passed as spread arguments at once, so we cant use the reducer style_.add
anymore. With Lodash 3 the following example works just fine:_.unzipWith
will insertundefined
s where the row is shorter than the others, and_.sum
treats undefined values as 0. (as of Lodash 3)If your input data can contain
undefined
andnull
items, and you want to treat those as 0, you can use this:This snipet works with Lodash 3, unfortunately I didn't find a nice way of treating undefined as 0 in Lodash 4, as now sum is changed so
_.sum([undefined]) === undefined
One-liner in
ES6
, withmap
andreduce
Assuming that the nested arrays will always have the same lengths, concat and reduce can be used.