Better way to sum a property value in an array
The best way to sum the property values in an array is through the use of the Array.prototype.reduce()
function:
Advanced reduce()
: Sum like a Boss
1. Basic isn't enough: handle multiple data types
Property values may not always be strictly numeric. We can avoid accidental string concatenation by casting them to Number
:
2. The smart way to sum: destructure properties
Make code more readable by destructuring within .reduce()
. Mind-saving stuff right here:
3. Summing in the real world: avoid missing properties
Filter out entries that don't have the required property. Not all apples have worms:
4. Go full throttle: summed properties served multiple ways
Sum multiple properties by chaining .reduce()
. Just like getting all the TV channels:
5. Going OOP: classes never go out of style
Put your summing logic neatly into a class. Warms your OOP-loving heart, doesn't it?:
Tidy and maintainable solutions for summing
1. Generic idioms: Boost code reusability
Craft a generic function to enhance code reusability. One function to rule them all:
2. The ES6 way: Boosters engaged
Harness the power of ES6, like arrow functions and the spread operator, for cleaner and more modern code:
3. Organisation is key: Clean your room with classes
Keeping relevant functions within classes can not only make your code more readable, but also feel more organised:
4. Just say "No": Protect native prototypes
Avoid extending native prototypes (such as Array.prototype) as it may lead to unexpected conflicts. Let's not open that can of worms:
Edge cases, loopholes and pitfalls to avoid
1. Sparse Arrays: No empty seats
.reduce()
ignores missing entries in sparse arrays. Initializing values can prevent errors. Hydra heads, be gone!:
2. Large Arrays: Bigger isn't always better
For larger arrays, consider the performance ramifications of iteration. Bigger isn't always better:
3. Immutability: First law of Array(otics)
Ensure that .reduce()
does not mutate the source or its objects. Pure function, pure heart:
4. Empty Arrays: Be prepared
Remember to provide .reduce()
with an initial value. Calling it on an empty array without a starting point will throw a TypeError:
Was this article helpful?