Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sum of array columns in JavaScript

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]
like image 568
Fikret Avatar asked Mar 30 '16 09:03

Fikret


People also ask

How do you sum all the specific fields of an object in an array?

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.


1 Answers

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>');
like image 152
Nina Scholz Avatar answered Sep 22 '22 17:09

Nina Scholz