EN
JavaScript - group objects by multiple properties in array then sum up their values
1
answers
0
points
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
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
References
0 comments
Add comment