Here is a quick tip on using 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, our new object has property 1 and property 2.
Now, if you expand 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 reuse it, we need to convert it 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;
}, {});
}