Map.groupBy()
The same grouping as Object.groupBy, into a Map instead. That one difference matters whenever the grouping key is not naturally a string.
Demo
The result is spread to pairs so the grouping is visible. Order within each bucket follows the input, and a group appears only if something landed in it — the second case has no 'even' entry at all, so map.get('even') is undefined rather than an empty array. The real advantage over Object.groupBy is invisible with string keys like these: return a Date or an object from the callback and it stays a Date or an object here, where Object.groupBy would stringify it.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| items | iterable | yes | Any iterable — an array, a Set, a generator. |
| callback | Function | yes | Called as callback(element, index). Its return value becomes the group key, used as-is with no coercion — matched by SameValueZero. |
Return value
Map — A Map from each key the callback returned to an array of the items that produced it. Keys keep their original type — nothing is stringified.
Common patterns
const byDate = Map.groupBy(events, e => e.date.getTime());
const byOwner = Map.groupBy(tasks, t => t.owner);
const odds = groups.get("odd") ?? [];
Examples
Pitfalls
Map.groupBy([1, 2], x => ({v: x % 2})).size
Map.groupBy([1, 2], x => x % 2).size
Map.groupBy([1], () => "odd").get("even").length
(Map.groupBy([1], () => "odd").get("even") ?? []).length
Map.groupBy([a, b], x => new Date(x.day)).size
Map.groupBy([a, b], x => new Date(x.day).getTime()).size
Map.groupBy(xs, f)
xs.reduce((m, x) => { const k = f(x); m.set(k, [...(m.get(k) ?? []), x]); return m; }, new Map())
When to use
- Grouping by a key that is not a string — a number, a Date value, an object reference
- Preserving the insertion order of first appearance for numeric keys
- Grouping where a key might collide with an object property name
- String keys you will serialise → Object.groupBy
- You want counts rather than items → map over the groups afterwards
- Keys are freshly created objects → every item gets its own group
- Targeting runtimes older than 2024 → a reduce
Notes
FAQ
Map.groupBy when the key is not a string — it stays a number, a Date, an object. Object.groupBy when string keys are natural and you want a plain object you can serialise. Object.groupBy also gives a null-prototype result, which has its own quirks.
Map.groupBy(xs, x => x.id); // number keys kept Object.groupBy(xs, x => x.status); // string keys, plain object