Languages

JavaScript - group object by property then sum up property values

0 points
Asked by:
Mikolaj
519

How can I group object by property then sum up property values?

Let's say I have the following array:

const array = [
    { id: 1, type: 'A', quantity: 1 },
    { id: 2, type: 'B', quantity: 1 },
    { id: 3, type: 'B', quantity: 2 },
    { id: 4, type: 'A', quantity: 2 },
    { id: 5, type: 'A', quantity: 2 }
];

I want to group its elements by type property value (2 groups: A and B) and then sum their quantities.

How can I do this?

1 answer
0 points
Answered by:
Mikolaj
519

The first thing you need to do is group array items, then sum the property values. The best way to do this is to use reduce() method.

Note:

You may want to check out those two articles that describes the solution below in details:

  1. JavaScript - group / grouping array items with reduce method

  2. JavaScript - sum property values in array of objects

Solution

In this solution I've combined two functions from the articles that I've mentioned above to group object by type property and then sum their quantities.

// ONLINE-RUNNER:browser;

const groupItems = (array, property) => {
    return array.reduce((groups, item) => {
        const name = item[property];
        const group = groups[name] || (groups[name] = []);
        group.push(item);
        return groups;
    }, {});
};

const sumProperty = (groups, property) => {
    const result = [];
    for (const group in groups) {
        const tmp = {};
        tmp[group] = groups[group].reduce((a, b) => a + (b[property] || 0), 0);
        result.push(tmp);
    }
    return result;
};


// Usage example:

const array = [
    { id: 1, type: 'A', quantity: 1 },
    { id: 2, type: 'B', quantity: 1 },
    { id: 3, type: 'B', quantity: 2 },
    { id: 4, type: 'A', quantity: 2 },
    { id: 5, type: 'A', quantity: 2 }
];

const groups = groupItems(array, 'type'); // array will be grouped by 'type' property

const quantities = sumProperty(groups, 'quantity');

console.log(JSON.stringify(quantities)); //[ { A: 5 }, { B: 3 } ]

 

See also

  1. JavaScript - group / grouping array items with reduce method

  2. JavaScript - sum property values in array of objects

References

  1. Array.prototype.reduce() - JavaScript | MDN
0 comments Add comment
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