Computer >> Computer tutorials >  >> Programming >> Javascript

How to group an array of objects by key in JavaScript


Suppose, we have an array of objects containing data about some cars like this −

const arr = [
   {
      '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'
   },
];

We are required to write a JavaScript function that takes in one such array of objects. The function should then group the objects together based on their 'make' property.

Output

Therefore, the output should look something like this −

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

Example

The code for this will be −

const arr = [
   {
      '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'
   },
];
const groupByMake = (arr = []) => {
   let result = [];
   result = arr.reduce((r, a) => {
      r[a.make] = r[a.make] || [];
      r[a.make].push(a);
      return r;
   }, Object.create(null));
   return result;
};
console.log(groupByMake(arr));

Output

And the output in the console will be −

{
   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' } ]
}