Explain Codes LogoExplain Codes Logo

Better way to sum a property value in an array

javascript
reduce
functions
promises
Nikita BarsukovbyNikita Barsukov·Oct 23, 2024
TLDR

The best way to sum the property values in an array is through the use of the Array.prototype.reduce() function:

const sum = array.reduce((total, obj) => total + obj.property, 0);

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:

const total = array.reduce((accumulator, obj) => accumulator + Number(obj.property), 0); // No more "1035" when summing 10 and "35"!

2. The smart way to sum: destructure properties

Make code more readable by destructuring within .reduce(). Mind-saving stuff right here:

const sumByProp = (arr, prop) => arr.reduce((total, { [prop]: value }) => total + Number(value), 0); // Now with a sprinkle of destructuring magic!

3. Summing in the real world: avoid missing properties

Filter out entries that don't have the required property. Not all apples have worms:

const validItems = array.filter(item => item.property !== undefined); const total = validItems.reduce((total, obj) => total + Number(obj.property), 0); // NaN has left the chat

4. Go full throttle: summed properties served multiple ways

Sum multiple properties by chaining .reduce(). Just like getting all the TV channels:

const sumProps = (array, props) => array.reduce((totals, item) => { props.forEach(prop => { totals[prop] = (totals[prop] || 0) + Number(item[prop]); }); return totals; }, {}); // Now in Technicolor!

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?:

class Summer { constructor(array) { this.array = array; // The Summer will be initialized with an array } sumByProp(prop) { return this.array.reduce((total, obj) => total + Number(obj[prop]), 0); // Remember, winter is coming! } }

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:

function sumObjectsByKey(array, key) { return array.reduce((accumulator, current) => { const keyValue = Number(current[key]) || 0; return accumulator + keyValue; }, 0); // Nothing gets past me - Missing properties will be zero }

2. The ES6 way: Boosters engaged

Harness the power of ES6, like arrow functions and the spread operator, for cleaner and more modern code:

const sumBy = (array, key) => array.reduce((total, { [key]: value }) => total + (value || 0), 0); class Summer { constructor(...properties) { this.properties = properties; } calculate(array) { return this.properties.map(prop => sumBy(array, prop)); } } // I've got the power of ES6 on my side!

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:

class PropertySummer { static sumByProperty(array, property) { return array.reduce((sum, item) => sum + Number(item[property]), 0); } } // PropertySummer: Cleaning up one object at a time

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:

// Bad James, don't touch the Array prototype! // Stick on creating your own functions or classes

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!:

// Note to self: Always prepare for sparse arrays

2. Large Arrays: Bigger isn't always better

For larger arrays, consider the performance ramifications of iteration. Bigger isn't always better:

// Avoid lag: If the array is too big, use alternative algorithms or data structures

3. Immutability: First law of Array(otics)

Ensure that .reduce() does not mutate the source or its objects. Pure function, pure heart:

// Surgeon's Note: No side effects please!

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:

// Let's avoid that awkward TypeError