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

如果我有这些对应的数组,里面有 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]);


子衿沉夜
浏览 162回答 3
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);

www说

您可以使用 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))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript