Map.groupBy()

The Map.groupBy() static method in JavaScript creates a Map object by grouping elements of an array based on a specified callback function. The callback determines the grouping key for each element.

Syntax

</>
Copy
Map.groupBy(items, callbackFn)

Parameters

ParameterDescription
itemsAn iterable (e.g., an array) whose elements will be grouped.
callbackFnA function that determines the grouping key for each element. It takes an item from items and returns a key used for grouping.

Return Value

The method returns a new Map object, where:

  • The keys are determined by the callbackFn.
  • The values are arrays containing elements that share the same key.

Examples

1. Grouping Numbers by Even and Odd

In this example, numbers are grouped based on whether they are even or odd.

</>
Copy
const numbers = [1, 2, 3, 4, 5, 6];

const groupedNumbers = Map.groupBy(numbers, num => num % 2 === 0 ? 'even' : 'odd');
console.log(groupedNumbers);

Output

Map(2) {
  'odd' => [1, 3, 5],
  'even' => [2, 4, 6]
}
  1. callbackFn checks if each number is even or odd and assigns a group.
  2. The result is a Map with keys 'odd' and 'even', each containing an array of corresponding numbers.

2. Grouping Strings by Length

This example groups words based on their length.

</>
Copy
const words = ["apple", "banana", "pear", "cherry", "fig"];

const groupedWords = Map.groupBy(words, word => word.length);
console.log(groupedWords);

Output

Map(3) {
  5 => ['apple', 'cherry'],
  6 => ['banana'],
  4 => ['pear', 'fig']
}
  1. callbackFn returns the length of each word as a grouping key.
  2. Words with the same length are grouped together.

3. Grouping Objects by a Property

This example groups a list of users based on their age.

</>
Copy
const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 25 },
  { name: "David", age: 30 }
];

const groupedUsers = Map.groupBy(users, user => user.age);
console.log(groupedUsers);

Output

Map(2) {
  25 => [{ name: "Alice", age: 25 }, { name: "Charlie", age: 25 }],
  30 => [{ name: "Bob", age: 30 }, { name: "David", age: 30 }]
}
  1. The callbackFn extracts the age property as the grouping key.
  2. Users with the same age are placed in the same group.

4. Grouping Dates by Year

This example groups an array of dates by year.

</>
Copy
const dates = [
  new Date("2022-06-15"),
  new Date("2023-07-20"),
  new Date("2022-01-10"),
  new Date("2023-12-05")
];

const groupedDates = Map.groupBy(dates, date => date.getFullYear());
console.log(groupedDates);

Output

Map(2) {
  2022 => [2022-06-15T00:00:00.000Z, 2022-01-10T00:00:00.000Z],
  2023 => [2023-07-20T00:00:00.000Z, 2023-12-05T00:00:00.000Z]
}
  1. The callbackFn extracts the year from each date.
  2. Dates are grouped into arrays under their respective years.