DEV Community

Ennio Bozzetti
Ennio Bozzetti

Posted on • Updated on

How to group an object by property

Here is a quick tip on how you can use Javascript reduce to group an array of objects by a property.

const students = [
  { name: 'John', grade: 1 },
  { name: 'James', grade: 1 },
  { name: 'Ryan', grade: 2 },
  { name: 'Matt', grade: 2 },
  { name: 'Joe', grade: 1 }
];

const groupedStudents = students.reduce((prev, cur) => {
  if (!prev[cur['grade']]) {
    prev[cur['grade']] = [];
  }

  prev[cur['grade']].push(cur);

  return prev;
}, {});

console.log(groupedStudents);
Enter fullscreen mode Exit fullscreen mode

Open your developer console and expand the object you see. As you can see, the object has two property 1 and 2. They are the grades from the original array, and since we ask to group the new object by grade, that is why our new object has property 1 and property 2.

Group Object

Now if you expand the property 1, you can see that we have an array of students and inside that array, you find all the students from grade 1, and if you do the same for property 2 you can see the students from grade 2

Detailed View

As you can see, this is a beneficial function, and we could reuse it in many places on our application. To be able to reuse it, we need to convert to a function, and that way we can pass the property we want to group by instead of hardcoding.

Here is our new function:

function groupedObj(objArray, property) {
  return objArray.reduce((prev, cur) => {
    if (!prev[cur[property]]) {
      prev[cur[property]] = [];
    }
    prev[cur[property]].push(cur);

    return prev;
  }, {});
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)