24

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?

3
  • 7
    to explain the issue - once you return the first sum, the typeof a will be a Number - which has no y property Commented Sep 26, 2016 at 8:59
  • check reduce function's callback parameters , what are they ? Commented Sep 26, 2016 at 8:59
  • 1
    Does this answer your question? Javascript reduce on array of objects Commented Apr 9, 2021 at 14:31

2 Answers 2

47

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

Sign up to request clarification or add additional context in comments.

2 Comments

one liner const reduced = temp.length ? temp.reduce((r, a) => { return r + a.y; }, 0) : 0;
@webmaster, even shorter, it takes the start value of reduce for empty arrays: const reduced = temp.reduce((r, { a }) => r + a, 0);
10

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.