Sub topic 10
Grouping Data with Map.groupBy
This chapter assumes you can create and read a Map, iterate it with for...of, and know that Map keys are compared with SameValueZero. It also assumes you are comfortable with arrow functions and arrays of objects.
What Map.groupBy does
Code often needs to sort a list into buckets: orders by status, files by extension, or users by role. Before ES2024 you wrote that loop yourself. Map.groupBy(items, callback) does it in one call. It calls callback(element, index) for each item, uses the return value as a key, and collects every item with the same key into an array.
const inventory = [
{ name: 'apple', type: 'fruit' },
{ name: 'carrot', type: 'vegetable' },
{ name: 'pear', type: 'fruit' }
];
const byType = Map.groupBy(inventory, (item) => item.type);
console.log(byType.get('fruit').map((item) => item.name)); // ['apple', 'pear']
console.log([...byType.keys()]); // ['fruit', 'vegetable']Map.groupBy is a static method on Map. It is not a method on arrays. It accepts any iterable, so Sets, generators, and map.values() all work as input.
Ordering and identity
The result follows two ordering rules:
- Keys appear in the order in which each key was first produced.
- Within a group, items keep the order in which the input yielded them.
The arrays hold the original items, not copies. If you change byType.get('fruit')[0].name, the object in inventory changes too.
Why use the Map version instead of Object.groupBy
Object.groupBy has the same signature but returns a null-prototype object. That object converts every key to a string or symbol. Map.groupBy keeps keys exactly as the callback returned them, and compares them with SameValueZero.
const nums = [1, 2, 3, 4, 5];
const asMap = Map.groupBy(nums, (n) => n % 2 === 0);
console.log(asMap.get(true)); // [2, 4]
console.log(asMap.get('true')); // undefined: the key is the boolean, not a string
const red = { label: 'Red' };
const blue = { label: 'Blue' };
const players = [
{ name: 'Ana', team: red },
{ name: 'Ben', team: blue },
{ name: 'Cy', team: red }
];
const byTeam = Map.groupBy(players, (p) => p.team);
console.log(byTeam.get(red).map((p) => p.name)); // ['Ana', 'Cy']
console.log(byTeam.size); // 2If you ran Object.groupBy on players, both teams would become the same key, "[object Object]", and the groups would merge.
| Need | Use |
|---|---|
| String keys, and the result goes straight to JSON | `Object.groupBy` |
| Object, boolean, or number keys | `Map.groupBy` |
| You need `size`, or you will add and delete groups later | `Map.groupBy` |
Common errors
- Calling it on the array.
inventory.groupBy(...)throws aTypeErrorbecause arrays have no such method. - Reading with bracket syntax.
byType['fruit']isundefined. UsebyType.get('fruit'). - Building a new object key in the callback.
(p) => ({ id: p.teamId })creates a fresh object on every call, so each item ends up in its own group. Return a primitive or a shared reference instead. - Older runtimes. You need Node 21+, Chrome 117+, Firefox 119+, or Safari 17.4+. On older runtimes, load a polyfill.
Exercise
What does Map.groupBy([1.5, 2.2, 1.9], Math.floor) return, and in what key order?
Show answer
It returns Map { 1 => [1.5, 1.9], 2 => [2.2] }. Math.floor receives the index as a second argument and ignores it. Key 1 comes first because 1.5 is the first item, and within that group 1.5 comes before 1.9 because that is the input order.
Exercise
A teammate writes Map.groupBy(orders, (o) => ({ status: o.status })) and gets one group per order. Why, and how do you fix it?
Show answer
Each call returns a new object, and SameValueZero compares objects by reference, so no two keys are ever equal. Return the primitive instead: (o) => o.status.