且构网

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

如何计算多个数组的总和?

更新时间:2023-02-10 15:55:38

这是另一种使用 reduce()生成了相应列的总数.

This is another approach that uses map() over the first array, nested with a reduce() that generated the total of the corresponding column.

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
];

const sums = list[0].map((x, idx) => list.reduce((sum, curr) => sum + curr[idx], 0));

console.log(sums);

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}