How to sum the values of a JavaScript object?

It can be as simple as that:

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

Quoting MDN:

The Object.values() method returns an array of a given object’s own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

from Object.values() on MDN

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

from Array.prototype.reduce() on MDN

You can use this function like that:

sumValues({a: 4, b: 6, c: -5, d: 0}); // gives 5

Note that this code uses some ECMAScript features which are not supported by some older browsers (like IE). You might need to use Babel to compile your code.

Leave a Comment