Grouping data in JavaScript made easy with Object.groupBy()
Use Object.groupBy() to group your data without using any loops
Grouping data in JavaScript used to be a pain. We had to iterate over the objects and push them into separate arrays. But now, thanks to the new Object.groupBy()
method, grouping data is a breeze!
Object.groupBy
Object.groupBy()` is a static method that groups array data by a property. Just pass in two arguments: the array and the callback function. The callback function is executed for each element in the array to determine its group.
suppose the following array is our data
const studentsArray = [
{
name: "John Doe",
age: 18,
grade: 12,
major: "Computer Science",
gpa: 3.8,
},
{
name: "Jane Doe",
age: 17,
grade: 11,
major: "English",
gpa: 3.6,
},
{
name: "Michael Smith",
age: 16,
grade: 10,
major: "Mathematics",
gpa: 4.0,
},
{
name: "Susan Jones",
age: 15,
grade: 9,
major: "History",
gpa: 3.2,
},
{
name: "David Williams",
age: 14,
grade: 8,
major: "Computer Science",
gpa: 3.4,
},
{
name: "Mary Brown",
age: 13,
grade: 7,
major: "Mathematics",
gpa: 3.1,
},
{
name: "Charles Miller",
age: 12,
grade: 6,
major: "History",
gpa: 3.0,
},
{
name: "Patricia Davis",
age: 11,
grade: 5,
major: "Physical Education",
gpa: 3.5,
},
{
name: "James Garcia",
age: 10,
grade: 4,
major: "Foreign Language",
gpa: 3.3,
},
{
name: "Jennifer Johnson",
age: 9,
grade: 3,
major: "Physical Education",
gpa: 3.7,
},
];
if we want to group them according to their major
then we will use the method like this
Object.groupBy(studentsArray,({major}) => major)
this will give us the following output
Now suppose we want to group them if their age is greater than 10
Object.groupBy(studentsArray,({age}) => age > 10);
then we will get false
for smaller than 10 and true
for greater than 10. We can use it in more ways to get our work done.
Thanks for reading.