How to group an object by property
Ennio Bozzetti
Posted on December 30, 2019
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);
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.
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
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;
}, {});
}
Posted on December 30, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024