Javascript - How to groupby an array objects in Javascript

Published May 10, 2021

In this javascript example we will learn how to use groupby function in javascript. To groupby an array objects we will use javascript reduce() function. This reduce() function will execute a reducer function on array object elements and return grouped array by key names.

 

Example

const employee= [
{ name: "Employee 1", salary: 15000 },
    { name: "Employee 1", salary: 30009 },
    { name: "Employee 2", salary: 40000 },
    { name: "Employee 2", salary: 70000 }

];

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(employee, 'salary');
console.log(groupedPeople);

 

 

Output:

 

[
   "Employee 1" : [
       { name: "Employee 1", salary: 15 },
       { name: "Employee 1", salary: 30 },
   ],
   "Employee 2" : [
       { name: "Employee 2", salary: 45 },
       { name: "Employee 2", salary: 70 }
   ],
]

 

 

Conclusion: we have learned how to use Javascript groupby fuction with reduce() method.

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

2946 Views