EN
JavaScript - reduce() on Object
0
points
In this article, we would like to show you how to use array reduce() method with objects in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const object = {
a: 1,
b: 2,
c: 3,
};
const sum = Object.values(object).reduce((x, y) => x + y);
console.log(sum); // 6
Practical example
In this example, we present a more complex example with nested objects. We use reduce() method to sum amount property values for all groups.
// ONLINE-RUNNER:browser;
const groups = {
group1: { amount: 1 },
group2: { amount: 2 },
group3: { amount: 3 },
};
const sum = Object.values(groups).reduce((x, { amount }) => x + amount, 0);
console.log(sum); // 6