如果我在这些具有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]);
答案 0 :(得分:3)
一个可能的解决方案是将第一个内部数组的每个元素Array.map()变为同一列中元素的总和。为了获得同一列中元素的汇总,我们可以在map()
内使用Array.reduce():
const nums = [
[4, 23, 20, 23, 6, 8, 4, 0],
[7, 5, 2, 2, 0, 0, 0, 0],
[1, 3, 4, 7, 1, 1, 1, 1],
];
let [first, ...rest] = nums;
let res = first.map((e, i) => rest.reduce((sum, x) => sum + x[i], e));
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 1 :(得分:3)
此功能支持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);
答案 2 :(得分:1)
您可以使用嵌套的forEach()
循环
const nums = [
[4, 23, 20, 23, 6, 8, 4, 0],
[7, 5, 2, 2, 0, 0, 0, 0]
];
function sum(arr){
let max = Math.max(...arr.map(x => x.length));
let res = Array(max).fill(0)
res.forEach((x,i) => {
nums.forEach(a => {
res[i] = res[i] + (a[i] || 0)
})
})
return res;
}
console.log(sum(nums))
答案 3 :(得分:1)
您可以使用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))
答案 4 :(得分:0)
获取最小长度subarray
,然后使用索引返回该长度的数组来创建该长度的数组。
const nums = [
[4, 23, 20, 23, 6, 8, 4, 0],
[7, 5, 2, 2, 0, 0, 0, 0]
];
const [arr1, arr2] = nums;
const min = Math.min(nums[0].length, nums[1].length);
const output = Array.from({length: min}, (_, i) => arr1[i] + arr2[i]);
console.log(output);