How to sum the Array of Objects in Javascript
In this tutorial, we are going to learn about how to sum the property of the array of objects in JavaScript with the help of examples.
Consider, we have the following array of objects:
const arr = [{vegetable: 'tomato', price: '2'},
{vegetable: 'cucumber', price: '3'},
{vegetable: 'beans', price: '4'}
];
Now, we need to calculate the sum of all vegetable prices from the above array.
Using the reduce() method
To sum the array of objects in JavaScript, we can use the built-in reduce() method by passing the array of the objects with the property value.
The reduce() method calls the reducer callback function on the each element of an array and returns the sum of all the elements in array as a single value.
Here is an example:
const arr = [{vegetable: 'tomato', price: 2},
{vegetable: 'cucumber', price: 3},
{vegetable: 'beans', price: 4}
];
const sum = arr.reduce((result, obj) => {
return result + obj.price;
}, 0);
console.log(sum);
Output:
9
Using the for of loop
We can use the for of loop in JavaScript to sum the property of an array of objects in array.
Here is an example:
const arr = [{vegetable: 'tomato', price: 2},
{vegetable: 'cucumber', price: 3},
{vegetable: 'beans', price: 4}
];
let sum = 0;
for (let obj of arr){
sum = sum + obj.price
}
console.log(sum);
In the above code, we have used the ‘for of loop’ to sum the array of the objects. Where on each iteration we are adding the property value of the object to the previous value to get the final sum.