In JavaScript, there often arises a need to group array elements based on a certain property. Prior to ES2024, this involved custom functions or using libraries like Lodash. However, ES2024 introduced a new, native method: Object.groupBy()
. This tutorial will show you how to use this method effectively.
The Object.groupBy()
method provides a concise way to group array elements based on custom criteria. It’s a welcome addition to JavaScript, making such operations more intuitive and reducing the need for external libraries, such as Lodash.
The Map.groupBy()
method provides a flexible way to group array elements using custom keys, including object keys. This allows for more semantically meaningful and complex groupings.
Understanding Object.groupBy()
The Object.groupBy()
method groups the elements of an array based on a provided callback function. The result is an object where the keys are the group names, and the values are arrays of elements belonging to each group.
Example Scenario
Let’s consider a simple example where we have an array of fruits, and we want to group them by their colour.
Step-by-Step Implementation
1. Defining the Array
First, let’s define an array of fruit objects, each with a name
and a color
property:
const fruits = [
{ name: 'pineapple 🍍', color: 'yellow' },
{ name: 'apple 🍎', color: 'red' },
{ name: 'banana 🍌', color: 'yellow' },
{ name: 'strawberry 🍓', color: 'red' },
{ name: 'kiwi 🥝', color: 'green' },
{ name: 'blueberry 🫐', color: 'blue' },
{ name: 'grape 🍇', color: 'purple' }
];
2. Grouping with Object.groupBy()
Next, we’ll use Object.groupBy()
to group the fruits by their colour:
const groupedByColor = Object.groupBy(
fruits,
(fruit) => fruit.color
);
console.log(groupedByColor);
How It Works
The callback function (fruit) => fruit.color
extracts the colour property from each fruit object. Object.groupBy()
then creates an object where each key is a colour, and the corresponding value is an array of fruits of that colour.
Output
Running the above code will produce the following output:
{
yellow: [
{ name: 'pineapple 🍍', color: 'yellow' },
{ name: 'banana 🍌', color: 'yellow' }
],
red: [
{ name: 'apple 🍎', color: 'red' },
{ name: 'strawberry 🍓', color: 'red' }
],
green: [
{ name: 'kiwi 🥝', color: 'green' }
],
blue: [
{ name: 'blueberry 🫐', color: 'blue' }
],
purple: [
{ name: 'grape 🍇', color: 'purple' }
]
}
Advanced Usage
Grouping by Multiple Criteria
You can also group by multiple criteria. For instance, if you had another property, like type
, you could group by both color
and type
:
const fruitsWithType = [
{ name: 'pineapple 🍍', color: 'yellow', type: 'tropical' },
{ name: 'apple 🍎', color: 'red', type: 'temperate' },
{ name: 'banana 🍌', color: 'yellow', type: 'tropical' },
{ name: 'strawberry 🍓', color: 'red', type: 'berry' },
{ name: 'kiwi 🥝', color: 'green', type: 'tropical' },
{ name: 'blueberry 🫐', color: 'blue', type: 'berry' },
{ name: 'grape 🍇', color: 'purple', type: 'berry' }
];
const groupedByColorAndType = Object.groupBy(
fruitsWithType,
(fruit) => `${fruit.color}-${fruit.type}`
);
console.log(groupedByColorAndType);
This will group the fruits by both colour and type, producing keys like "yellow-tropical"
and "red-berry"
.
Grouping Arrays with Object Keys using Map.groupBy()
JavaScript’s ES2024 introduced the Map.groupBy()
method, which allows for flexible and powerful grouping of array elements. This method groups array elements into a Map
, based on a grouping function, and can handle object keys as well.
Example Scenario
Consider an example where we want to group numbers into odd and even categories, and use object keys for better semantic clarity.
Step-by-Step Implementation
1. Defining the Array
First, let’s define a simple array of numbers:
const array = [1, 2, 3, 4, 5];
2. Defining the Grouping Keys
Next, we define the object keys that we will use for grouping:
const odd = { odd: true };
const even = { even: true };
3. Grouping with Map.groupBy()
We use Map.groupBy()
to group the numbers based on their odd or even status:
const groupedByOddEven = Map.groupBy(array, (num) => {
return num % 2 === 0 ? even : odd;
});
console.log(groupedByOddEven);
How It Works
The grouping function (num) => num % 2 === 0 ? even : odd
checks whether each number is even or odd. If a number is even, it returns the even
object as the key; otherwise, it returns the odd
object.
Output
Running the above code will produce the following output:
Map(2) {
{ odd: true } => [1, 3, 5],
{ even: true } => [2, 4]
}
Advanced Usage
Grouping Complex Objects
You can group more complex objects using a similar approach. Let’s say we have an array of student objects, and we want to group them by their grade level:
const students = [
{ name: 'Alice', grade: 9 },
{ name: 'Bob', grade: 10 },
{ name: 'Charlie', grade: 9 },
{ name: 'David', grade: 11 },
{ name: 'Eve', grade: 10 }
];
const grade9 = { grade: 9 };
const grade10 = { grade: 10 };
const grade11 = { grade: 11 };
const groupedByGrade = Map.groupBy(students, (student) => {
switch (student.grade) {
case 9:
return grade9;
case 10:
return grade10;
case 11:
return grade11;
}
});
console.log(groupedByGrade);
Output
This will produce:
Map(3) {
{ grade: 9 } => [
{ name: 'Alice', grade: 9 },
{ name: 'Charlie', grade: 9 }
],
{ grade: 10 } => [
{ name: 'Bob', grade: 10 },
{ name: 'Eve', grade: 10 }
],
{ grade: 11 } => [
{ name: 'David', grade: 11 }
]
}