Let's say I have a array that contains a multiple object like:
var arr = [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}]
I want to get a sum of all credit
value from arr
array. so expected sum value is 3. so I used this code:
arr.reduce((obj, total) => obj.credit + total)
but when I run this, I get "1[object Object]"
which is really weird.
Ps: I'm trying to implement this using ES6 not ES5
Two problems: your total
and obj
arguments are backwards, and you need to provide something to initialize the total
variable (that's the ,0
part)
arr.reduce((total, obj) => obj.credit + total,0)
// 3