We have arrays:
[1, 2, 3, 0]
[1, 2, 3]
[1, 2]
Need to get a one array, indexes which is will be like a sum of columns. Expected result:
[3, 6, 6, 0]
To sum a property in an array of objects:Call the reduce() method to iterate over the array. On each iteration increment the sum with the specific value. The result will contain the sum of the values for the specific property.
You can use Array.prototype.reduce()
in combination with Array.prototype.forEach()
.
var array = [
[1, 2, 3, 0],
[1, 2, 3],
[1, 2]
],
result = array.reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = (r[i] || 0) + b;
});
return r;
}, []);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With