DEV Community

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

Posted on

2 1

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!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs