Does anyone know of a (lodash if possible too) way to group an array of objects by an object key then create a new array of objects based on the grouping? For example, I hav
Here is another solution to it. As requested.
I want to make a new array of car objects that's grouped by make:
function groupBy() {
const key = 'make';
return cars.reduce((acc, x) => ({
...acc,
[x[key]]: (!acc[x[key]]) ? [{
model: x.model,
year: x.year
}] : [...acc[x[key]], {
model: x.model,
year: x.year
}]
}), {})
}
Output:
console.log('Grouped by make key:',groupBy())