JavaScript Map.groupBy()
Syntax & Examples

Map.groupBy() static-method

The groupBy static method of the Map object in JavaScript groups the elements of a given iterable using the values returned by a provided callback function. The final returned Map uses the unique values from the test function as keys, which can be used to get the array of elements in each group.


Syntax of Map.groupBy()

The syntax of Map.groupBy() static-method is:

Map.groupBy(items, callbackFn)

This groupBy() static-method of Map groups the elements of a given iterable using the values returned by a provided callback function. The final returned Map uses the unique values from the test function as keys, which can be used to get the array of elements in each group.

Parameters

ParameterOptional/RequiredDescription
itemsrequiredAn iterable (e.g., an array) containing the elements to be grouped.
callbackFnrequiredA callback function that accepts each element of the iterable as its argument and returns the value to be used for grouping.

Return Type

Map.groupBy() returns value of type Map.



✐ Examples

1 Using groupBy to group elements by their lengths

In JavaScript, we can use the groupBy static method of the Map object to group elements of an array based on their lengths.

For example,

  1. Create an array items with elements of varying lengths.
  2. Define a callback function callbackFn that returns the length of each element.
  3. Use the groupBy method to group the elements of items by their lengths.
  4. Log the resulting Map to the console using console.log().

JavaScript Program

const items = ['apple', 'banana', 'cherry', 'pear', 'grapefruit'];
const callbackFn = item => item.length;
const groupedMap = Map.groupBy(items, callbackFn);
console.log(groupedMap);

Output

{
  5 => ['apple', 'pear'],
  6 => ['banana', 'cherry'],
  10 => ['grapefruit']
}

2 Using groupBy to group elements by their first letters

In JavaScript, we can use the groupBy static method of the Map object to group elements of an array based on their first letters.

For example,

  1. Create an array items with elements starting with different letters.
  2. Define a callback function callbackFn that returns the first letter of each element.
  3. Use the groupBy method to group the elements of items by their first letters.
  4. Log the resulting Map to the console using console.log().

JavaScript Program

const items = ['apple', 'banana', 'cherry', 'pear', 'grapefruit'];
const callbackFn = item => item[0];
const groupedMap = Map.groupBy(items, callbackFn);
console.log(groupedMap);

Output

{
  'a' => ['apple'],
  'b' => ['banana'],
  'c' => ['cherry'],
  'p' => ['pear'],
  'g' => ['grapefruit']
}

Summary

In this JavaScript tutorial, we learned about groupBy() static-method of Map: the syntax and few working examples with output and detailed explanation for each example.