Let's take a closer look at
_.groupBy(), one of the array methods in Lodash.
# lodash groupBy() methodThis method is very convenient for rearranging a collection based on a specific value of the collection as a property.
In other words, as the name "groupBy" suggests, it returns results grouped by a specific value. For instance, let's assume we have a collection of student data. This data has grades A, B, C, D, F for student performances, and if you need to reclassify them based on each grade, it can be used easily and conveniently. Let's start with the syntax.
_.groupBy(Data, PropertyName)The simple syntax is as shown above.
Data //
The array or collection data to be rearrangedPropertyName //
The name of the property to be used as a criterionWhat happens when the above method is executed? It's rearranged, categorized by the value of the object that has the PropertyName. The following example will make it clearer.
Now, let's create a simple example below.
! lodash groupBy() exampleBelow is the data containing students' names and grades. This method uses lodash's groupBy() to get data rearranged by grade.
students = [
{
name: 'Tom',
grade: 'C'
},
{
name: 'Steve',
grade: 'A'
},
{
name: 'Robert',
grade: 'B'
},
{
name: 'Ethan',
grade: 'A'
},
{
name: 'James',
grade: 'C'
}
]
Now, we will obtain the array values rearranged based on the "grade" property.
studentByGrade = _.groupBy(students, 'grade')
// Result
{
A: [
{name: 'Steve', grade: 'A'}
{name: 'Ethan', grade: 'A'}
],
B: [
{name: 'Robert', grade: 'B'}
],
C: [
{name: 'Tom', grade: 'C'}
{name: 'James', grade: 'C'}
]
}
Seeing the result makes it clear. You can see that it's rearranged according to the list grouped by grade.
It's a frequently used and convenient method for sorting large amounts of data. That's a brief overview of lodash's groupBy().