简体   繁体   中英

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()

// 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

Try this aproach, using a map nested with a 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM