JavaScript Reference ยท Array
Map.groupBy() and array grouping
Reference for JavaScript Map.groupBy(): group the items of an array or any iterable into a Map by a key function, and how it differs from Object.groupBy().
Map.groupBy() is a static method that sorts the items of an iterable (usually an array) into groups. You pass the items and a callback that returns a key for each item. The result is a Map whose keys are those returned keys and whose values are arrays of the items that got that key.
Because the result is a Map, keys can be any value: strings, numbers, objects or booleans. If you only need string keys and prefer a plain object, there is a sibling method, Object.groupBy(). There is no Array.prototype.groupBy(); grouping lives on the constructors.
const groups = Map.groupBy([1, 2, 3, 4], (n) => n % 2 === 0); // Map { false => [1, 3], true => [2, 4] }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Map.groupBy(items, callbackFn)
| Name | Description |
|---|---|
items |
An iterable, such as an array, string, Set or generator. |
callbackFn |
A function called once per item as callbackFn(item, index). It returns the key of the group the item belongs to. |
Return value: a new Map. Each key is a value returned by the callback; each value is an array of the items that produced that key, in the original order. Groups appear in the order their keys were first seen.
Exceptions: TypeError if items is not iterable or callbackFn is not a function.
Usage notes
- Keys follow Map rules. They are compared with SameValueZero, so
NaNgroups together and0and-0are the same key. Two different objects are two different keys, even if they look alike. - Items are not copied. The group arrays contain the original values (or object references).
- Missing group.
get()returnsundefinedfor a key nobody produced; check before using the result, for examplemap.get(key) ?? []. Object.groupBy()returns a null-prototype object whose keys are converted to strings (or symbols). Use it when you want to read results with dot or bracket access or serialize them to JSON; useMap.groupBy()when keys are not strings.- Non-mutating. The input is never changed, and the callback should not change it either.
- Before
groupBy, the usual pattern was areduce()or a loop that creates the group array on first use. The new methods replace that boilerplate. - Counting instead of collecting. If you only need counts, loop once and keep a
Mapof numbers; building every group array wastes memory.
Browser support
Map.groupBy() and Object.groupBy() are recent additions. They work in current browsers and recent Node.js versions, but check a compatibility table before relying on them for older environments.