How To Sum A Property In An Array Of Objects In JavaScript

Sometimes you have to sum a Property in an Array of Objects in JavaScript. This article will show you two ways: using the reduce() function and the array.forEach(). Let’s focus on the explanations and examples below to understand more about these two methods.

Sum a Property in an Array of Objects in JavaScript

Using the reduce() function

The reduce() function is the function provided by JavaScript to reduce the array’s values into a single value. This method executes a reducer function provided for an array component from left to right, stores the function’s return value in the accumulator variable, and does not change the original array.

The reduce() function is commonly applied to sum a Property in an Object Array in JavaScript.

Syntax:

arr.reduce((acc, arr) => { return acc + arr.id}, 0);

Parameter:

  • acc: Accumulator, which is used to store the sum of the values of the property
  • arr: The array to which the current element belongs.

Example:

Let’s try to calculate the number of cars in this array.

const car = [
    { name: "Toyota", amount: 5 },
    { name: "BMW", amount: 5 },
    { name: "Lexus", amount: 10 },
    { name: "Ford", amount: 10 },
];

const sum = car.reduce((acc, car) => {
    return acc + car.amount;
}, 0);

console.log("The number of cars is " + sum);

Output:

The number of cars is 30

Using the array.forEach()

Array.forEach() is an array object method in JavaScript. This method will call the provided function, which is the callback function, once for each element in the array and store the element’s value in each iteration in a passed parameter. 

To sum a Property in an Array of Objects in this way, we need to add the values of the elements to a storage variable after each loop.

Syntax:

array.forEach(function(currentValue, index, arr), thisValue)

Parameter:

  • currentValue ( Required parameter): The value of an array.
  • index ( Optional parameter): The index of the current element.
  • arr ( Optional parameter): The array of the current element.
  • thisValue ( Optional parameter): The parameter holds the value passed to the function.

Example:

Let’s calculate the number of cars in the “car” array.

const car = [
    { name: "Toyota", amount: 5 },
    { name: "BMW", amount: 5 },
    { name: "Lexus", amount: 10 },
    { name: "Ford", amount: 10 },
];

// Initialize storage variable
let total = 0;

car.forEach(function (car) {
    total += car.amount;
});

console.log("The number of cars is " + total);

Output:

The number of cars is 30

Summary

In the above article, I have introduced two methods to sum a Property in an Array of Objects in JavaScript. Depending on your project, you can utilize one of two ways or discover other ways, which are more appropriate. Hope this article can assist you.

Leave a Reply

Your email address will not be published. Required fields are marked *