Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reduce is not giving right sum

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?

like image 349
daydreamer Avatar asked Jun 15 '13 20:06

daydreamer


1 Answers

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

like image 62
Ry- Avatar answered Sep 22 '22 20:09

Ry-