group by array of objects by key

How to Group By Array of Objects by Key

JavaScript allows you to store data as an array of items where all items can be of same or different data types. You can even store objects (key-value pairs) in arrays making it easy to store diverse data in a compact manner. Sometimes you may need to group by array of objects by key. Typically, such tasks are done in back-end databases using SQL queries. But you can also do it in JavaScript. In this article, we will learn how to group by array of objects by key.


How to Group By Array of Objects by Key

Let us say you have the following array of objects, each containing the make, model and year of cars.

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

Let us say you want to group by array elements by the ‘make’ key as shown below.

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

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

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

We will learn how to do the above transformation using plain JavaScript as well as third party libraries such as lodash.


1. Using JavaScript

Every JS array supports a reduce function that allows you to iterate over each array item and perform tasks on them, while storing & using the result of previous iterations.

result = cars.reduce(function (r, a) {
        r[a.make] = r[a.make] || [];
        r[a.make].push(a);
        return r;
    }, Object.create(null));

console.log(result);

The above function goes through each object in array, and does either of two things – either create a new array for the make or push the current array object into the existing array for the make. But the above code will retain key value pair for ‘make’ key in each object.

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

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

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

If you want to remove the make key-value from the result, modify your reduce function as shown below.

result = cars.reduce(function (r, a) {
        r[a.make] = r[a.make] || [];
        r[a.make].push({'model':a.model,'year':a.year});
        return r;
    }, Object.create(null));

console.log(result);


2. Using Lodash

Lodash is a third party JS library that offers many useful functions. You need to include the following code in your web page in order to import this library.

<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>

Once you have imported the above library, you can easily reduce the array to group by ‘make’ key, as well as remove the key from your final result, as shown below.

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

console.log(grouped);

In the above code, _.mapValues does the work of reduce() function shown above. _.groupBy does the grouping. We specify the array name, and the key to be grouped by. We also use _.omit() function to omit the ‘make’ key from result.

Here is the result you can get when you call the above console.log() function.

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

In this article, we have learnt how to group by array of objects using plain JavaScript as well as using Lodash library. You can also use other JS libraries for the same purpose.

Typically, the above operation is done in databases using SQL queries with GROUP BY clauses. If your data is stored in databases, then it is also advisable to use SQL queries or other means to do the grouping in databases itself, instead of doing it in JavaScript, since databases are built to perform such operations on large amounts of data quickly.

Also read:

How to Find Element Using XPath in JavaScript
How to Remove Submodule in Git
How to Merge Two Git Repositories
How to Setup Git Username & Password for Different Repos
How to Reset Git Credentials

Leave a Reply

Your email address will not be published. Required fields are marked *