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.
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.
Parameter | Optional/Required | Description |
---|---|---|
items | required | An iterable (e.g., an array) containing the elements to be grouped. |
callbackFn | required | A callback function that accepts each element of the iterable as its argument and returns the value to be used for grouping. |
Map.groupBy() returns value of type Map
.
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,
items
with elements of varying lengths.callbackFn
that returns the length of each element.groupBy
method to group the elements of items
by their lengths.console.log()
.const items = ['apple', 'banana', 'cherry', 'pear', 'grapefruit'];
const callbackFn = item => item.length;
const groupedMap = Map.groupBy(items, callbackFn);
console.log(groupedMap);
{ 5 => ['apple', 'pear'], 6 => ['banana', 'cherry'], 10 => ['grapefruit'] }
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,
items
with elements starting with different letters.callbackFn
that returns the first letter of each element.groupBy
method to group the elements of items
by their first letters.console.log()
.const items = ['apple', 'banana', 'cherry', 'pear', 'grapefruit'];
const callbackFn = item => item[0];
const groupedMap = Map.groupBy(items, callbackFn);
console.log(groupedMap);
{ 'a' => ['apple'], 'b' => ['banana'], 'c' => ['cherry'], 'p' => ['pear'], 'g' => ['grapefruit'] }
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.