How to Sum Values in Array of Objects in JavaScript
To sum values in an array of objects in JavaScript, use the
reduce() method to accumulate the total by accessing the desired property in each object. For example, array.reduce((sum, obj) => sum + obj.value, 0) adds all value properties together.Syntax
The reduce() method processes each object in the array and keeps a running total. It takes a function with two parameters: the accumulator (total so far) and the current object. The second argument to reduce() is the initial value of the accumulator, usually 0 for sums.
array.reduce((accumulator, currentObject) => accumulator + currentObject.property, initialValue)accumulator: holds the sum as it buildscurrentObject: the current object in the arrayproperty: the key of the value to suminitialValue: starting point for the sum, usually 0
javascript
array.reduce((accumulator, currentObject) => accumulator + currentObject.property, 0)Example
This example shows how to sum the price values in an array of product objects.
javascript
const products = [ { name: 'Apple', price: 1.2 }, { name: 'Banana', price: 0.8 }, { name: 'Cherry', price: 2.5 } ]; const totalPrice = products.reduce((sum, product) => sum + product.price, 0); console.log(totalPrice);
Output
4.5
Common Pitfalls
Common mistakes include:
- Not providing the initial value to
reduce(), which can cause errors or unexpected results. - Trying to sum properties that are missing or not numbers, leading to
NaNresults. - Using
forEachwithout accumulating a sum variable externally, which is less concise.
javascript
const items = [ { value: 10 }, { value: '5' }, // string instead of number { value: 15 } ]; // Wrong: no initial value and string included const wrongSum = items.reduce((acc, obj) => acc + obj.value); console.log(wrongSum); // Outputs '10515' (string concatenation) // Right: convert to number and provide initial value const correctSum = items.reduce((acc, obj) => acc + Number(obj.value), 0); console.log(correctSum); // Outputs 30
Output
10515
30
Quick Reference
Tips for summing values in array of objects:
- Always provide an initial value (usually 0) to
reduce(). - Ensure the property you sum exists and is a number.
- Use
Number()orparseFloat()to convert strings to numbers if needed. - Use
reduce()for concise and readable summing.
Key Takeaways
Use the reduce() method with an initial value to sum object properties safely.
Always check that the property exists and is a number to avoid NaN results.
Convert string numbers to actual numbers before summing if needed.
Avoid forgetting the initial value to prevent unexpected behavior.
reduce() provides a clean and efficient way to sum values in arrays of objects.