Languages
[Edit]
EN

JavaScript - reduce() on Object

0 points
Created by:
Kevin
797

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

 

References

  1. Array.prototype.reduce() - JavaScript | MDN

Alternative titles

  1. JavaScript - array reduce() with Object
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join