How to call reduce on an array of objects to sum their properties?

Say I want to sum a.x for each element in arr.

arr = [ { x: 1 }, { x: 2 }, { x: 4 } ];
arr.reduce(function(a, b){ return a.x + b.x; }); // => NaN

I have cause to believe that a.x is undefined at some point.

The following works fine

arr = [ 1, 2, 4 ];
arr.reduce(function(a, b){ return a + b; }); // => 7

What am I doing wrong in the first example?

20 Answers
20

Leave a Comment