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
I love to write it with no dependency/complexity just pure simple js.
const mp = {}
const cars = [
{
model: 'Imaginary space craft SpaceX model',
year: '2025'
},
{
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'
}
]
cars.forEach(c => {
if (!c.make) return // exit (maybe add them to a "no_make" category)
if (!mp[c.make]) mp[c.make] = [{ model: c.model, year: c.year }]
else mp[c.make].push({ model: c.model, year: c.year })
})
console.log(mp)