user1547174 user1547174 - 15 days ago 5
Javascript Question

How to group array of objects by key

does anyone know of a lodash 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 have an array of car objects:

var 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'
},

];


I want to make a new array of car objects that's grouped by
make
:

var cars = [

'audi': [
{
'model': 'r8',
'year': '2012'
},
{
'model': 'rs5',
'year': '2013'
},
],

'ford': [
{
'model': 'mustang',
'year': '2012'
},
{
'model': 'fusion',
'year': '2015'
}
],

'kia': [
{
'model': 'optima',
'year': '2012'
}
]

]


I know how to do it in vanilla javascript, but wanted to see if anyone knows of an efficient lodash way... Thanks in advance!

Answer

You are looking for _.groupBy().

Removing the property you are grouping by from the objects should be trivial if required:

var 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'},];

var grouped = _.groupBy(cars, function(car) {
  return car.make;
});

console.log(grouped);
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>


As a bonus, you get even nicer syntax with ES6 arrow functions:

const grouped = _.groupBy(cars, car => car.make);