Map.groupBy
Groups elements into a Map by any key.
Available since: ES2024
Syntax
Map.groupBy(items, callbackFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| items | Iterable | An array or another iterable. |
| callbackFn | Function | A function that returns the group key for an element. |
Return value
MapA Map in which each key maps to an array of the group's elements.
Examples
Grouping by a numeric key:
const words = ['hi', 'cat', 'yo', 'dog', 'horse'];
const byLength = Map.groupBy(words, (word) => word.length);
console.log(byLength.get(2).join(', '));
console.log(byLength.get(3).join(', '));
console.log([...byLength.keys()].join(', '));Output:
hi, yo
cat, dog
2, 3, 5Notes
The difference from Object.groupBy(): keys are not converted to strings, so they can be numbers, objects or any other values.
See also
- Object.groupBy — Groups the elements of an array by a key.
- Map — A collection of key–value pairs where a key can be anything.
Related recipes
In the tutorial
- Map and Set — The Map and Set collections in JavaScript: a dictionary with keys of any type and a set of unique values.