Languages

JavaScript - group objects by multiple properties in array then sum up their values

0 points
Asked by:
Inayah-Alexander
767

How can I group the array below by country and type property and then sum up their quantity property values?

const array = [
    { country: 'USA',    type: 'A', quantity: 1 },
    { country: 'USA',    type: 'A', quantity: 2 },
    { country: 'Canada', type: 'B', quantity: 1 },
    { country: 'Canada', type: 'B', quantity: 2 },
    { country: 'USA',    type: 'A', quantity: 2 }
];

I want the result to be like this:

{
  { country: 'USA',    type: 'A', quantity: 5 },
  { country: 'Canada', type: 'B', quantity: 3 }
}
1 answer
0 points
Answered by:
Inayah-Alexander
767

You can use reduce() method to create temporary object with unique groups as its properties. Then inside each group sum up the property value of all objects.

// ONLINE-RUNNER:browser;

const groupAndSum = (array, property1, property2, propertyToSum) => {
    const tmp = {};
    array.reduce((result, object) => {
        const group = object[property1] + '-' + object[property2];
        if (!tmp[group]) {
            tmp[group] = Object.assign({}, object);
            result.push(tmp[group]);
        } else {
            tmp[group][propertyToSum] += object[propertyToSum];
        }
        return result;
    }, []);
    return tmp;
};


// Usage example:

const array = [
    { country: 'USA',    type: 'A', quantity: 1 },
    { country: 'USA',    type: 'A', quantity: 2 },
    { country: 'Canada', type: 'B', quantity: 1 },
    { country: 'Canada', type: 'B', quantity: 2 },
    { country: 'USA',    type: 'A', quantity: 2 },
];

const result = groupAndSum(array, 'type', 'country', 'quantity');

console.log(JSON.stringify(result, null, 4));

 

See also

  1. JavaScript - group object by property then sum up property values

References

  1. Array.prototype.reduce() - JavaScript | MDN
  2. Object.assign() - 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