DEV Community

Cover image for Using reduce() on an array of objects

Posted on

Using reduce() on an array of objects

array of objects
Here we have an array of objects labeled arrayOfObjects which holds 3 objects, labeled objectOne, objectTwo, objectThree. Each object holds 1 property labeled propertyOne.

array of objects, property values highlighted
Let’s use the reduce() function to sum all the values of each object’s property, propertyOne. (50 + 60 + 70)

reduce method and result
But this returns an unexpected result! We got a String concatenation:
[object Object] + 60 + 70

reduce method and result highlighted
Reduce() requires 2 arguments, the initialValue to start with, and the currentValue being looked at. But because this is an array of objects, the initial value is an object, so Reduce() doesn’t know how to add this to 60 and 70, which results in the string concatenation.

reduce method and result with 3rd argument
But Reduce() takes an optional argument, which comes outside of the callback function and tells Reduce() what initialValue to start with, in this case, we use 0. currentValue starts on index 0 and because we’re looking at currentValue.propertyOne, will add 50 on the first iteration.

Now the process has all the same types, Number, and proceeds to sum all values of propertyOne:
0 + 50 + 60 + 70
correct sum
And console.log now prints the correct sum!

Top comments (0)