sum of array of objects javascript

Sum of Array of Objects in JavaScript

As a JavaScript developer, I have come across a situation where I needed to sum the values of an array of objects. It can be challenging to perform arithmetic operations on arrays of objects, but fortunately, there are simple ways to achieve this in JavaScript.

Method 1: Using the reduce() method

The reduce() method is a powerful built-in function in JavaScript that allows you to perform complex operations on arrays. It takes a callback function as its argument, which is executed for each element in the array. The reduce() method returns a single value that is the result of the callback function executed on each element of the array.

const arr = [
  {value: 10},
  {value: 20},
  {value: 30},
  {value: 40}
];

const sum = arr.reduce((accumulator, currentValue) => {
  return accumulator + currentValue.value;
}, 0);

console.log(sum); // Output: 100

In the above example, we have an array of objects containing the value property. We use the reduce() method to sum up all the values in the array. The initial value of the accumulator is set to 0, and then we add up each object's value property to it.

Method 2: Using a for loop

If you are not comfortable using the reduce() method, you can also use a for loop to achieve the same result. In this method, we loop through each object in the array and add up its value to a variable called sum.

const arr = [
  {value: 10},
  {value: 20},
  {value: 30},
  {value: 40}
];

let sum = 0;

for(let i = 0; i < arr.length; i++) {
  sum += arr[i].value;
}

console.log(sum); // Output: 100

In the above example, we initialize the sum variable to 0 and then loop through each object in the array using a for loop. Inside the loop, we add up the value property of each object to the sum variable.

Conclusion

Summing up the values of an array of objects in JavaScript can be achieved using various methods. The reduce() method is a powerful built-in function that can perform complex operations on arrays. However, if you are not comfortable using it, a simple for loop can also get the job done. It is essential to choose the method that best suits your coding style and requirements.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe