EN
JavaScript - group object by property then sum up property values
1
answers
0
points
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
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:
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
References
0 comments
Add comment