Group by element in array JavaScript


Suppose, we have an array of objects like this −

const arr = [
   {"name": "toto", "uuid": 1111},
   {"name": "tata", "uuid": 2222},
   {"name": "titi", "uuid": 1111}
];

We are required to write a JavaScript function that splits the objects into separate array of arrays that have the similar values for the uuid property.

Output

Therefore, the output should look like this −

const output = [
   [
      {"name": "toto", "uuid": 1111},
      {"name": "titi", "uuid": 1111}
   ],
   [
      {"name": "tata", "uuid": 2222}
   ]
];

The code for this will be −

const arr = [
   {"name": "toto", "uuid": 1111},
   {"name": "tata", "uuid": 2222},
   {"name": "titi", "uuid": 1111}
];
const groupByElement = arr => {
   const hash = Object.create(null),
   result = [];
   arr.forEach(el => {
      if (!hash[el.uuid]) {
         hash[el.uuid] = [];
         result.push(hash[el.uuid]);
      };
      hash[el.uuid].push(el);
   });
   return result;
};
console.log(groupByElement(arr));

Output

The output in the console −

[
   [ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
   [ { name: 'tata', uuid: 2222 } ]
]

Updated on: 10-Oct-2020

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements