ArticleZip > How To Call Reduce On An Array Of Objects To Sum Their Properties

How To Call Reduce On An Array Of Objects To Sum Their Properties

In JavaScript, the `reduce` method is a powerful tool when working with arrays. It allows you to transform an array into a single value based on the logic you provide. When dealing with an array of objects and wanting to sum the values of a specific property across all objects, you can leverage `reduce` effectively.

First and foremost, you need to have an array of objects that you want to work with. Each object in the array should have a property holding a numerical value that you wish to sum. Let's say you have an array of objects representing products, and each object has a `price` property that holds the price of the product.

So, to sum up all the prices of these products, you can use the `reduce` method. Here's how you can achieve this:

Javascript

const products = [
  { name: 'Product 1', price: 10 },
  { name: 'Product 2', price: 20 },
  { name: 'Product 3', price: 30 }
];

const totalPrices = products.reduce((accumulator, currentProduct) => {
  return accumulator + currentProduct.price;
}, 0);

console.log(totalPrices); // Output: 60

In the given example, `reduce` takes two main arguments: a callback function and an initial value for the accumulator. The callback function receives two parameters: the accumulator (which holds the interim result) and the current item being iterated over in the array.

The callback function calculates the sum by adding the `price` property of each product to the accumulator. The initial value of the accumulator is set to 0, which is the starting point for the sum.

It's essential to provide a starting value for the accumulator, or else it will default to the first element of the array by default. In this case, starting with a value of 0 ensures that the sum is performed correctly across all objects in the array.

Additionally, if you want to perform the sum of a specific property nested within the objects, you can access it using dot notation or bracket notation within the callback function. For instance, if the price was nested under `details`, you would access it like `currentProduct.details.price`.

By using `reduce` in this manner, you can easily and efficiently sum up specific properties across an array of objects in JavaScript. It's a versatile method that allows for a wide range of transformations on arrays, making your code more concise and readable.

So, next time you need to sum up properties in an array of objects, remember to reach for the `reduce` method and simplify your code while still achieving the desired result efficiently. Happy coding!

×