Author -  Sai gowtham

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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY