How to Sum a Property in an Array of Objects in JavaScript?

31-May-2023

.

Admin

How to Sum a Property in an Array of Objects in JavaScript?

I will explain step by step tutorial how to sum a property in an array of objects in javascript. if you want to see example of javascript sum array of objects value – examples then you are a right place. I would like to show you javascript - sum values of objects in array. I would like to share with you javascript - how to find the sum of an array of numbers.

To sum a property in an array of objects in JavaScript, you can use the reduce() method. Here's an example:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Sum a Property in an Array of Objects in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const items = [

{ name: "item1", price: 10 },

{ name: "item2", price: 20 },

{ name: "item3", price: 30 }

];

const totalPrice = items.reduce((acc, item) => acc + item.price, 0);

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

</script>

</html>

In this example, we have an array of objects that represent items with their respective prices. We want to calculate the total price by summing the `price` property of each object.

We use the reduce() method on the `items` array and pass a callback function as its argument. The callback function takes two parameters - `acc` (accumulator) and `item`. The accumulator is initialized to zero (0) as the second argument to reduce().

Inside the callback function, we add the current `item.price` value to the accumulator (`acc`). Finally, reduce() returns the accumulated value which is our total price.

Note that if your property contains non-numeric values, you may need to convert them to numbers before summing them up.

#JavaScript