且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数组数组中相同索引处的元素加到一个数组中?

更新时间:2023-10-15 12:06:28

你可以使用 Array.prototype.reduce() Array.prototype.forEach()

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