How to call reduce on an array of objects to sum their properties?
To sum the values of a specific property from an array of objects, utilize the .reduce() function, providing an initial value:
Note: Make sure the property name (score) matches the keys in your objects.
Prepping for the big reduce
Before utilizing .reduce(), it is critical to supply an initial value. This small step enables handling of empty arrays and undefined properties, effectively side-stepping errors such as NaN. What's more, if you're a TypeScript enthusiast, this initial value ensures type inference for the accumulator.
Making magic with destructuring
When using .reduce(), you have the power to destructure the current object for a easier access to specific properties:
Embrace destructuring to tell your code's story better.
Quick draw with ES6 arrow Functions
The ES6 arrow function offers a cleaner syntax for .reduce(), that's faster than the Millennium Falcon :
Mutate not with initial values
Immutability is core to functional programming. Avoid mutations by providing an initial value to .reduce().
Handling the layers: Nested structures
When confronted with arrays of arrays or objects with nested arrays, flatten the array before using .reduce() :
Superpowers with Map-Reduce
When the property to be summed is buried deeper or needs transformation before reduction, come to the rescue with .map() chained with .reduce() :
Trying-on practical tips
Guardians of property-existence
Before marching onto property summing, verify if the property even exists. This can be our guard clause against pesky runtime errors:
Wrestling with mixed data types
When your array is a cocktail of types, you must sanitize your data or affirm conditions in your reducing function to make sure the sum is not wonky:
Transducers for performance
Enjoy the thrill of transducers for complex transformations. These combine transformations and reduce them to a performant single operation:
Wielding the practical power of reduce
Parameters - More the merrier
.reduce() function actually accepts four parameters: accumulator, current item, item index, and the entire array. These optional parameters open a world of more complex scenarios:
The power beyond numbers
.reduce() is a versatile tool, enabling reduction of an array to any value type: strings, objects, or even functions:
Advanced - Custom flattening
If you encounter labyrinth-like nested arrays or complex JSON structures, draw upon a specialized flattening function with .reduce():
Was this article helpful?