Sum property values of an object in Javascript
April 08, 2020
TLDR
1.const sumValues = obj => Object.values(obj).reduce((a, b) => a + b);
Usage
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:
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:
1.values.reduce((a, b) => a + b);
The iterations will look something like this:
Iteration | Accumulator | Current Value | Operation |
1 | 0 | 1 | 0 + 1 |
2 | 1 | 2 | 1 + 2 |
3 | 3 | 3 | 3 + 3 |
4 | 6 | 4 | 6 + 4 |
End | 10 |
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.
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.}