Let's say I have an array of objects:
[
{
category: 'Category A',
mainUnits: 5,
subUnits: 3
},
{
category: 'Category A',
mainUnits: 9,
subUnits, 12
},
{
category: 'Category B',
mainUnits: 4,
subUnits, 6
},
{
category: 'Category B',
mainUnits: 2,
subUnits, 4
}
]
However, I can't seem to get an array that looks like this:
[
{
category: 'Category A',
mainUnits: 14,
subUnits: 15
},
{
category: 'Category B',
mainUnits: 6,
subUnits: 10
}
]
I have been able to make some sort of headway, but can't quite get the exact result I need. Any guidance is greatly appreciated, thanks!
The .reduce array method seems like a good fit here.
Use the array .find method to see if there is already an item with that category in the result. If so, add the fields, but if not, add the item to the result:
const input = [{
category: 'Category A',
mainUnits: 5,
subUnits: 3
}, {
category: 'Category A',
mainUnits: 9,
subUnits: 12,
}, {
category: 'Category B',
mainUnits: 4,
subUnits: 6,
}, {
category: 'Category B',
mainUnits: 2,
subUnits: 4,
}];
const result = input.reduce((result, item) => {
const existing = result.find(x => x.category === item.category);
if (existing) {
existing.mainUnits += item.mainUnits;
existing.subUnits += item.subUnits;
} else {
result.push(item);
}
return result;
}, []);
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With