I'm struggling to come up with an efficient way of grouping array of objects by a property into another array.
I checked some solutions from related questions and answers however struggling to achieve needed data structure.
Sample data incoming data (taken from this q)
const cars = [{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
}, ];
here is what I'm trying to achieve:
const carsTransformed = [{
'audi': [{
'model': 'r8',
'year': '2012'
}, {
'model': 'rs5',
'year': '2013'
},],
},
{
'ford': [{
'model': 'mustang',
'year': '2012'
}, {
'model': 'fusion',
'year': '2015'
}],
},
{
'kia': [{
'model': 'optima',
'year': '2012'
}]
}
];
so far tried to use
const arrayGroupBy = (array, property) => {
return array.reduce((map, object) => {
(map[object[property]] = map[object[property]] || []).push(object);
return map;
}, {});
};
with some attempts to manipulate resulting object via Object.entries(obj).map()
getting some weird results :(
I'll appreciate any ideas on how to achieve this.
Edit: Trying to not use any third party libraries.