简体   繁体   English

请我希望在我的JavaScript数组数组上使用reduce方法

[英]Please I wish to use the reduce method on my javascript array of arrays

I have a total array that has other arrays of values inside. 我有一个总数组,里面有其他值数组。 I wish to add the nested values with the help of forEach and reduce() 我希望在forEach和reduce()的帮助下添加嵌套值

// My main array
Total = [
  [ 1, 0, 1, 0 ],
  [ 0, 1, 0, 0 ],
  [ 1, 0, 0, 1 ],
  [ 0, 0, 1, 0 ],
  [ 0, 1, 0, 0 ],
  [ 1, 0, 0, 0 ],
  [ 0, 0, 0, 0 ],
  [ 0, 0, 0, 0 ] ]

// The code I have

  Total.forEach(function(element) {
    element.reduce(function(a,b) {
        console.log(a+b)
    }, 0)
})

// Output not as expected!
    1
NaNNaNNaN0 NaNNaNNaN1 NaNNaNNaN0 NaNNaNNaN0 NaNNaNNaN1 []

What I want is for example, The first forEach should give the sum of 1+0+1+0 = 2... And so on 例如,我想要的是,第一个forEach应该给出1+0+1+0 = 2...的总和。

Try this aproach, using a map nested with a reduce : 使用嵌套有reduce地图尝试此方法:

 const Total = [ [1, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]; let res = Total.map(x => x.reduce((res, curr) => res += curr, 0)); console.log(res); 

you can try this code 你可以试试这个代码

 var Total = [ [ 1, 0, 1, 0 ], [ 0, 1, 0, 0 ], [ 1, 0, 0, 1 ], [ 0, 0, 1, 0 ], [ 0, 1, 0, 0 ], [ 1, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]; function myFunction(){ for(let i=0 ;i<Total.length;i++){ console.log(Total[i].reduce(getSum)); } } function getSum(total, num) { return total + num; } myFunction(); 

Hope this helps 希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript - 减少数组数组 - Javascript - Reduce array of arrays Javascript:使用 reduce() 方法在数组中查找 LCM - Javascript: Use reduce() method to find the LCM in an array JavaScript:使用Reduce方法将多个数组合并为一个数组 - JavaScript: Using Reduce Method to Merge Together Multiple Arrays Into One Array 如果我在 TypeScript 中定义数组,但当我使用 model 文件时,为什么我的 reduce() 方法有效? - Why is my reduce() method working if I define the array in the TypeScript but not when I use a model file? 如何在 loDash 中使用 reduce 方法? 或者 Javascript 获取一组对象并创建一个对象 - How do I use the reduce method in loDash? Or Javascript Take a Array of Objects and Make one Object 扩展使用Javascript array.reduce辅助方法 - Expanding use of Javascript array.reduce helper method 如何让Javascript的reduce方法在数组数组上工作? - How can I make Javascript's reduce method work on arrays of arrays? Javascript:如何使用reduce function 和concat 数组function 将数组ZA3CBC549D0CE2D71C 转换为一个数组? - Javascript: How to use the reduce function and the concat array function to transform an array of arrays into an array? Javascript,使用reduce数组方法 - Javascript, using the reduce array method 我可以将函数变成变量以减少代码吗(请调试JavaScript代码) - can I make a function into a variable to reduce my code (JavaScript Code debug Please)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM