To reduce an array of objects in JavaScript, you can use the “array.reduce()” method. The array.reduce() method is “used to reduce an array of objects to a single value by executing a callback function for each array element”.
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameters
function: It is a callback function.
- total: It is the function’s initial value or the previously returned value.
- currentValue: It is the value of the current item in an array.
- currentIndex: It is the index of the current element.
- arr: It is the array object to which the current element belongs.
- initialValue: It is a value to be passed to the function as the initial value.
Return value
The value results from running the “reducer” callback function to completion over the entire array.
Example
const mainArray = [
{ values: 21 },
{ values: 19 },
{ values: 46 }
];
// A callback function that adds up two values
const addValues = (total, currentValue) => {
return total + currentValue.values;
};
// Using reduce() to get the sum of all values
const sum = mainArray.reduce(addValues, 0); // Initial value is 0
console.log(sum);
Output
86
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
“Sum of values in an object array” – why is an initialvalue of 0 necessary?