How can I calculate the sum of specific property values in an array of objects in JavaScript?
Alex K
alex k profile pic

To calculate the sum of specific property values in an array of objects in JavaScript, you can use various approaches, such as using a loop, thereduce() method, or a combination ofmap() andreduce(). Here are examples of each approach: 1. Using a loop:

1
2
3
4
5
6
7
8
9

   function calculateSum(objects, property) {
     let sum = 0;
     for (let i = 0; i < objects.length; i++) {
       sum += objects[i][property];
     }
     return sum;
   }
   

In this example, thecalculateSum function takes an array of objects,objects, and the property name,property, as parameters. It uses a loop to iterate over each object and adds the corresponding property value to thesum variable. Finally, it returns the calculated sum. 2. Using thereduce() method:

1
2
3
4
5

   function calculateSum(objects, property) {
     return objects.reduce((sum, obj) => sum + obj[property], 0);
   }
   

Thereduce() method iterates over the array, accumulating a value (thesum) based on each object's property value. It takes a callback function as the first argument, which receives the accumulator (sum) and the current object (obj). The callback function adds the property value to thesum, starting from an initial value of 0. 3. Usingmap() andreduce():

1
2
3
4
5
6
7

   function calculateSum(objects, property) {
     return objects
       .map((obj) => obj[property])
       .reduce((sum, value) => sum + value, 0);
   }
   

In this approach, themap() method is used to create a new array containing only the property values of the objects. Then, thereduce() method calculates the sum of the values in the newly created array. Here's an example usage of thecalculateSum function:

1
2
3
4
5
6
7
8
9

const items = [
  { name: 'Item 1', price: 10 },
  { name: 'Item 2', price: 20 },
  { name: 'Item 3', price: 30 },
];

const total = calculateSum(items, 'price');
console.log(total); // Output: 60

In this example, thecalculateSum function is called with an array of objects (items) and the property name'price'. It calculates the sum of theprice property for each object in the array, resulting in a total of 60. You can modify thecalculateSum function according to your specific needs, such as handling edge cases or validating the input.