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

前端 未结 6 982
陌清茗
陌清茗 2020-12-03 03:05

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 t

6条回答
  •  日久生厌
    2020-12-03 03:58

    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('
    ' + JSON.stringify(result, 0, 4) + '
    ');

    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);

提交回复
热议问题