javascriptarraysgrouping

How can I group an array of objects by key?


Does anyone know of a way (lodash if possible too) 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:

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

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

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

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

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

Solution

  • Timo's answer is how I would do it. Simple _.groupBy, and allow some duplications in the objects in the grouped structure.

    However the OP also asked for the duplicate make keys to be removed. If you wanted to go all the way:

    var grouped = _.mapValues(_.groupBy(cars, 'make'),
                              clist => clist.map(car => _.omit(car, 'make')));
    
    console.log(grouped);
    

    Yields:

    { audi:
       [ { model: 'r8', year: '2012' },
         { model: 'rs5', year: '2013' } ],
      ford:
       [ { model: 'mustang', year: '2012' },
         { model: 'fusion', year: '2015' } ],
      kia: 
       [ { model: 'optima', year: '2012' } ] 
    }
    

    If you wanted to do this using Underscore.js, note that its version of _.mapValues is called _.mapObject.