Sum property values of an object in Javascript

April 08, 2020

javascript

TLDR

js
1.const sumValues = obj => Object.values(obj).reduce((a, b) => a + b);

Usage

js
1.const obj = { a: 1, b: 2, c: 3, d: 4 };
2.
3.const sum = sumValues(obj);
4.
5.// 10

Sum values of an object with .reduce()

First, get the values of each property using the Object.values() function:

js
1.const obj = { a: 1, b: 2, c: 3, d: 4 };
2.const values = object.values(obj);
3.
4.// [1,2,3,4]

Object.values() returns an array of the objects property values. We can use the .reduce() array method on that array to sum up all the values into a single value. The .reduce() method takes a function as a parameter which accepts four arguments but only the first two are important for our purposes: the accumulator and the current value. The accumulator represents the accumulated value from the last operation on the array, while the current value represents the current item in the array we are looking at. To sum up all the values we simply need to sum the accumulator (all the past values summed) with the current value:

js
1.values.reduce((a, b) => a + b);

The iterations will look something like this:

IterationAccumulatorCurrent ValueOperation
1010 + 1
2121 + 2
3333 + 3
4646 + 4
End10

Sum values of an object with for..in in Javascript

Another interesting way to sum object values in Javascript is with for..in loop, which iterates over properties of an object. We can sum up the values with for..in by creating a variable total and adding the next value within the for..in loop to the total variable.

js
1.const obj = { a: 1, b: 2, c: 3, d: 4 };
2.
3.let total = 0;
4.
5.for (let value in object) {
6. total += obj[value];
7.}