gpt4 book ai didi

javascript - 根据索引的嵌套数组的总和

转载 作者:搜寻专家 更新时间:2023-10-30 22:04:38 26 4
gpt4 key购买 nike

如果我有这些相应的数组,里面有 2 个嵌套数组(这可能有 2 个或更多):

const nums = [
[4, 23, 20, 23, 6, 8, 4, 0], // Each array consists of 8 items
[7, 5, 2, 2, 0, 0, 0, 0]
];

如何根据索引对它们进行加法?

预期结果:

// 11 is from 4 (array1 - index1) + 7 (array2 - index1)
// and so on.
[11, 28, 22, 25, 6, 8, 4, 0]

我所做的是:

// This will work but it will only be applicable for 2 arrays as what if there will be 2 or more making it dynamic 

const total = Array.from({ length: 8 }, (_, i) => nums[0][i] + nums[1][i]);

最佳答案

这支持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);

关于javascript - 根据索引的嵌套数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56178760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com