How to sum elements at the same index in array of arrays into a single array?

You can use Array.prototype.reduce() in combination with Array.prototype.forEach().

var array = [
        [0, 1, 3],
        [2, 4, 6],
        [5, 5, 7],
        [10, 0, 3]
    ],
    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>');

Update, a shorter approach by taking a map for reducing the array.

var array = [[0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3]],
    result = array.reduce((r, a) => a.map((b, i) => (r[i] || 0) + b), []);
    
console.log(result);

Leave a Comment