What is the most efficient way to groupby objects in an array?
For example:
[{
"month": "October",
"active_users": 20,
"invited_users": 35
},
{
"month": "October",
"active_users": 50,
"invited_users": 60
},
{
"month": "September",
"active_users": 10,
"invited_users": 45
},
{
"month": "September",
"active_users": 80,
"invited_users": 95
}]
I want to group similar objects based on the 'month' key, I have taken the reference from here for grouping the similar objects but I want to do some further calculations.
I tried with this:
const data = [{
"month": "October",
"active_users": 20,
"invited_users": 35
},
{
"month": "October",
"active_users": 50,
"invited_users": 60
},
{
"month": "September",
"active_users": 10,
"invited_users": 45
},
{
"month": "September",
"active_users": 80,
"invited_users": 95
}]
function groupBy(objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
// Add object to list for given key's value
acc[key].push(obj);
return acc;
}, {});
}
const groupedData = groupBy(data, 'month');
console.log(groupedData);
My expected result is:
[{
"month": "October",
"active_users": 70,
"invited_users": 95
},
{
"month": "September",
"active_users": 90,
"invited_users": 140
}
]
I want to add remaining values of keys of similar objects, what is the most efficient way to achieve this?