How do you use reduce on an array of objects to sum their properties?
For instance, I want to sum the x property for each element in the arr:
arr = [ { x: 1 }, { x: 2 }, { x: 4 } ];
arr.reduce(function(a, b){ return a.x + b.x; }); // => NaN
The following works perfectly fine:
arr = [ 1, 2, 4 ];
arr.reduce(function(a, b){ return a + b; }); // => 7
What am I doing wrong in the first example when using JavaScript to reduce an array of objects?
Ah, I totally get where you’re coming from! It’s a common hiccup. The problem lies in the accumulator’s starting value. When you use reduce
, the first time it runs, it tries to access a.x
, but since a
is undefined at that point, you get NaN
. Just set an initial value for the accumulator to 0. It should look like this:
arr.reduce(function(a, b) { return a + b.x; }, 0); // => 7
This way, you’re safely starting with a number, and the summing will work smoothly.
Great point, Yanisleidi! I’ve found another way to approach this, especially if you want to keep the accumulator as an object for each iteration. In that case, just make sure to initialize a
as an object that has the x
property set to 0. Here’s how you can do it:
arr.reduce(function(a, b) { return { x: a.x + b.x }; }, { x: 0 }).x; // => 7
This method keeps it clear that you’re working with objects, and the result is nicely wrapped in an object as well.
Absolutely, Akansha! I’ve also found that destructuring the objects within the callback can make the code even clearer. It allows you to avoid referencing a.x
directly, which can lead to confusion if a
is undefined on the first call. Check this out:
arr.reduce(({ x: sum }, { x }) => sum + x, 0); // => 7
This approach is concise and directly sums up the x
values, making it an elegant solution when using javascript reduce array of objects. Plus, it’s super readable!