Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling reduce to sum array of objects returns NaN

I have code similar to this:

var temp = [ { "y": 32 }, { "y": 60 }, { "y": 60 } ];
var reduced = temp.reduce(function(a, b) {
  return a.y + b.y;
});

console.log(reduced); // Prints NaN

Why does it print NaN instead of 152?

like image 765
Akhilesh Kumar Avatar asked Sep 26 '16 08:09

Akhilesh Kumar


2 Answers

short solution: map the collection to integers collection, and reduce it

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];

var reduced = temp
                .map(function(obj) { return obj.y; })
                .reduce(function(a, b) { return a + b; });

console.log(reduced);
like image 150
Chen Avatar answered Nov 15 '22 18:11

Chen


You could use a start value and the add only one value from the array.

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];

var reduced = temp.reduce(function (r, a) {
        return r + a.y;
        //    ^^^ use the last result without property
    }, 0);
//   ^^^ add a start value
console.log(reduced) // r
like image 40
Nina Scholz Avatar answered Nov 15 '22 20:11

Nina Scholz