Here we have an array of objects labeled arrayOfObjects which holds 3 objects, labeled objectOne, objectTwo, objectThree. Each object holds 1 property labeled propertyOne.
Let’s use the reduce() function to sum all the values of each object’s property, propertyOne. (50 + 60 + 70)
But this returns an unexpected result! We got a String concatenation:
[object Object] + 60 + 70
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.
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
And console.log now prints the correct sum!
Top comments (0)