Most efficient method to groupby on an array of objects in Javascript


The most efficient method to group by a key on an array of objects in js is to use the reduce function.

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Example

const people = [
   { name: 'Lee', age: 21 },
   { name: 'Ajay', age: 20 },
   { name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
   return objectArray.reduce((acc, obj) => {
      const key = obj[property];
      if (!acc[key]) {
         acc[key] = [];
      }
      // Add object to list for given key's value
      acc[key].push(obj);
      return acc;
   }, {});
}
const groupedPeople = groupBy(people, 'age');
console.log(groupedPeople);

Output

This will give the output −

{ 20: [ { name: 'Ajay', age: 20 }, { name: 'Jane', age: 20 } ],
21: [ { name: 'Lee', age: 21 } ] }

Updated on: 27-Nov-2019

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements