Reputation: 92179
My Object groupBy.Food
looks like
[
Object
amount: "15.0"
category: Object
debit: true
__proto__: Object
,
Object
amount: "10.0"
category: Object
debit: true
__proto__: Object
,
Object
amount: "11.1"
category: Object
debit: true
__proto__: Object
]
All I want is sum
of amount in each object. I am using Lodash reduce as
var s = _.reduce(groupBy.Food, function(s, entry){
return s + parseFloat(entry.amount);
});
When I see value of s
I get
s
"[object Object]1011.1"
What is that I am not doing right here?
Upvotes: 12
Views: 9915
Reputation: 440
You can also use _.sum(array)
or _.sumBy(array, [iteratee=_.identity])
for summing up for both array and object. See below examples.
_.sum([4, 2, 8, 6]); // ➜ 20
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.sumBy(objects, function(o) { return o.n; }); // ➜ 20
_.sumBy(objects, 'n');// ➜ 20
Upvotes: 7
Reputation: 225291
By default, reduce
starts out with the first two items in the list, so s
will be the first item in the array and entry
will be the second item the first time your function is called. Give it a value to start with:
var s = _.reduce(groupBy.Food, function(s, entry) {
return s + parseFloat(entry.amount);
}, 0);
(Array
’s reduce
behaves the same way.)
Upvotes: 25