3 回答
TA贡献1906条经验 获得超10个赞
这支持 n 个嵌套数组
const nums = [
[4, 23, 20, 23, 6, 8, 4, 0],
[7, 5, 2, 2, 0, 0, 0, 0],
[2, 1, 2, 5, 7, 8, 9, 4]
];
const total = nums.reduce((a, b) => a.map((c, i) => c + b[i]));
console.log(total);
TA贡献1775条经验 获得超8个赞
您可以使用 reduce 和内部循环。需要注意的一些事情是不同的数组长度和不是数字的值。
const nums = [
[4, 23, 20, 23, 6, 8, 4, 0], // Each array consists of 8 items
[7, 5, 2, 2, 0, 0, 0, 0]
];
const otherNums = [
[4, 23, 20, 23, 6, 8, 4, 0, 9, 55], // Each array consists of 8 items
[7, 5, 2, 2, 0, 0, 0, 0, "cat", null, 78],
[7, 5, 2, 2, 0, 0, 0, 0, "dog", null, 78],
[7, 5, 2, 2, 0, 0, 0, 0, "elephant", null, 78]
];
const sumArraysByIndex = nums => nums.reduce((sums, array) => {
for (const index in array) {
if (sums[index] === undefined) sums[index] = 0
if (isNaN(array[index])) return sums
sums[index] += array[index]
}
return sums
}, [])
console.log(sumArraysByIndex(nums))
console.log(sumArraysByIndex(otherNums))
添加回答
举报