I am using this reduce by i need to calculate not only for category but for level too.
so I will have an array of objects that will include count of mainUnits and subUnits for each category and each level so for example
{
category: 1,
mainUnits: 14,
subUnits: 15,
levelA: {
mainUnits: 4,
subUnits: 6
},
levelB: {
mainUnits: 14,
subUnits: 15
}
}
const input = [
{
category: 1,
level: 'B',
mainUnits: 5,
subUnits: 3,
},
{
category: 1,
level: 'B',
mainUnits: 9,
subUnits: 12,
},
{
category: 2,
level: 'A',
mainUnits: 4,
subUnits: 6,
},
{
category: 2,
level: '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);
3
Answers
You could group with an object and get the values as result. Inside check for level and add an object with properties with zero values.
Then add for outer and nested level the units.
Lodash approach using
groupBy
,sumBy
andmapValues
:I have added a couple more lines of code to your working snippet and it does the job. Let me know if I missed something.