Sum the Values of an Object Array in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 14 20212 min read

banner

Photo by David Solce

Sum the Values of an Object Array #

To sum the values of an array of objects:

  1. Call the reduce() method to iterate over the array, passing it a function as the first parameter and an initial value of 0 as the second.
  2. On each iteration increment the sum with the value of the current object.
index.js
const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; const sum = arr.reduce((accumulator, object) => { return accumulator + object.salary; }, 0); console.log(sum); // ๐Ÿ‘‰๏ธ 60

The function we passed to the Array.reduce method gets invoked with each element (object) in the array.

The accumulator parameter gets an initial value of 0, because that's what we supplied as the second parameter to the reduce method.

For each object in the array, we increment the accumulator by the salary value in the object.

The reduce method returns the sum of the salary values of all objects in the array.

An alternative and perhaps simpler approach is to use the forEach method.

To sum the values of an array of objects:

  1. Initialize a sum variable, using the let keyword and set it to 0.
  2. Call the forEach() method to iterate over the array.
  3. On each iteration, increment the sum variable with the value of the object.
index.js
const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; let sum = 0; arr.forEach(element => { sum += element.salary; }); console.log(sum); // ๐Ÿ‘‰๏ธ 60

The function we pass to the Array.forEach method gets called with each element in the array.

Notice that we declare the sum variable using the let keyword. We can't reassign variables declared using const.

On each iteration of the loop, we increment the value stored in the sum variable to get the total amount.

This approach is more readable and intuitive, especially if you're not used to how the reduce method works.

The forEach method is not supported in Internet Explorer. If you have to support the browser, you can use a basic for loop instead.
index.js
const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; let sum = 0; for (let index = 0; index < arr.length; index++) { sum += arr[index].salary; } console.log(sum); // ๐Ÿ‘‰๏ธ 60

This code snippet achieves the same goal, however instead of the forEach method, we use a basic for loop.

Instead of accessing the element directly, we have to use the index of each iteration. This is a bit indirect and cluttered, however most developers are used to reading for loops.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee