Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reduce to sum up all values in array of object failed

I got [object Object]9778177 as result, I tried to parse the value but doesn't help neither, something is wrong.

let x = [{
  "total_count": 7
}, {
  "total_count": 9
}, {
  "total_count": 778
}, {
  "total_count": 177
}]

let sum = x.reduce((accum, obj) => {
   return accum + obj.total_count
})

console.log(sum)
like image 482
Jessie Anderson Avatar asked Aug 11 '17 06:08

Jessie Anderson


1 Answers

You could add a start value, because the first iteration starts with the object for the accumulator and there you have not the property, you would need.

let sum = x.reduce((accum, obj) => accum + obj.total_count, 0);
like image 82
Nina Scholz Avatar answered Oct 24 '22 18:10

Nina Scholz