This post will discuss the process of finding and using the sum of an array’s objects using JavaScript.
How to Add/Sum Array Objects?
In JavaScript, you can utilize the following methods to calculate the sum of an array of objects:
We will now go through each of the above-mentioned methods one by one.
Method 1: Using for Loop to Find the Sum of Array of Objects
This method involves the use of the “for” loop where the array of objects is added by specifying the property on which the addition needs to be done.
Let’s check out the below-given example for a better understanding.
Example
Firstly, we will define an array of objects as follows:
{name: 'x', id: 1},
{name: 'y', id: 2},
{name: 'z', id: 3},
];
Next, we will create a variable named “add” initialized with the “0” value to avoid null value. This variable will be utilized in the for loop to store the required sum:
Then, add a for loop and control its execution using the “i” iterator and the “array.length” property. Within the for loop, the sum of the values of the “id” property will be stored in the “add” variable, and after each iteration, its value gets updated:
{
add += array[i].id
}
Lastly, we will print the updated added values of the array of objects on the console.
The output of the above program will display “6” as the sum of the “id” property values:
Move ahead to learn the second method for finding the sum of an array of objects.
Method 2: Using reduce() Method to Find the Sum of Array of Objects
For the purpose of finding the sum of the array of objects, the “reduce()” method is also utilized. This method merges the value of the previous and current objects, which will be reduced to a single value.
Example
Firstly, we will declare an array and assign different values to the same properties of both objects:
"id": 1,
"roll" : 10
}, {
"id": 2,
"roll" : 15
}];
Next, we will compute the sum of objects in an array for the “id”, “roll” properties and reduce them to a single resultant value:
return {
id: previousValue.id + currentValue.id,
roll: previousValue.roll + currentValue.roll,
}
});
Finally, display the resultant value of both the objects on the console screen:
The resultant sum of the “id” is “3” and for “roll”, it is “25”:
We have provided the methods related to the sum of an array of objects in JavaScript.
Conclusion
To calculate the sum of an array of objects, the “for” loop and “reduce()” methods of the array class can be utilized in JavaScript. These mentioned methods assist in calculating the sum of the values of the specified object properties. Moreover, you can also perform various other operations for handling the object. This article guided about the procedure of using the sum of an array of objects in JavaScript.