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