Sub topic 10
Grouping Data with Map.groupBy
Grouping means splitting a list into buckets, where every item in a bucket shares some property. You might group orders by customer, log lines by severity, or test scores by letter grade. Before ES2024, you wrote this by hand with reduce or a loop. Map.groupBy now does it in one call and returns a Map.
This chapter assumes you know the Map API (get, set, has, size), insertion-order iteration of Maps, SameValueZero key equality, and array methods such as map and reduce. It also assumes arrow functions and the spread operator.
The Basic Call
Map.groupBy(items, callback) takes an iterable and a function. It calls the function once for each item. Whatever the function returns becomes the group key, and the item is appended to that key's 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']groupBy is a static method. You call it on the Map constructor itself, not on an array or on a Map instance. inventory.groupBy(...) does not exist.
The result follows a few fixed rules:
- Each key is a value the callback returned.
- Each value is a new array of the matching items, in the order they appeared in the input.
- Keys appear in the Map in the order each key was first produced.
- Keys are compared with SameValueZero, the same rule
Map.prototype.setuses.
Key Order Comes From First Appearance
Learners often expect the groups to be sorted. They are not sorted. The first item that produces a key decides where that key sits in the Map.
const scores = [72, 95, 88, 41, 67, 90];
const byGrade = Map.groupBy(scores, (score) => {
if (score >= 90) return 'A';
if (score >= 70) return 'B';
return 'C';
});
console.log([...byGrade.keys()]); // ['B', 'A', 'C']
console.log(byGrade.get('A')); // [95, 90]The first score, 72, is a B, so 'B' comes first. If you need a specific order, sort the keys after grouping, or sort the input before grouping.
The Callback Receives the Index
The callback is called with two arguments: the item and its zero-based index. Unlike Array.prototype.map, it does not receive the whole collection as a third argument. The index is enough for positional grouping such as chunking.
const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const chunks = Map.groupBy(letters, (_, index) => Math.floor(index / 3));
console.log([...chunks.values()]); // [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]Any Iterable Works
The first argument does not have to be an array. A Set, a string, a generator, or the entries of another Map all work, because groupBy reads its input with the iteration protocol.
function* numbers() {
yield 1; yield 2; yield 3; yield 4; yield 5;
}
const parity = Map.groupBy(numbers(), (n) => (n % 2 === 0 ? 'even' : 'odd'));
console.log(parity.get('odd')); // [1, 3, 5]
const ids = new Set([10, 15, 20]);
const bySize = Map.groupBy(ids, (id) => (id > 12 ? 'big' : 'small'));
console.log(bySize.get('big')); // [15, 20]An empty iterable gives an empty Map. A non-iterable first argument, or a callback that is not a function, throws a TypeError. If the callback throws partway through, the error propagates and you get no partial result.
Why a Map and Not an Object
JavaScript also has Object.groupBy, which takes the same arguments and returns a plain object with a null prototype. The difference is in what the keys can be.
| Aspect | Map.groupBy | Object.groupBy |
|---|---|---|
| Return type | `Map` | Object with `null` prototype |
| Key types | Any value, including objects | Strings and symbols; other values are converted to strings |
| Key equality | SameValueZero | Property key equality after string conversion |
| Key order | First appearance | First appearance, except integer-like keys, which come first in ascending order |
| Works with `JSON.stringify` directly | No | Yes |
The key type matters most. Suppose your items reference shared role objects:
const admin = { label: 'Admin' };
const editor = { label: 'Editor' };
const users = [
{ name: 'Ana', role: admin },
{ name: 'Ben', role: editor },
{ name: 'Cy', role: admin }
];
const byRole = Map.groupBy(users, (user) => user.role);
console.log(byRole.size); // 2
console.log(byRole.get(admin).map((u) => u.name)); // ['Ana', 'Cy']
const broken = Object.groupBy(users, (user) => user.role);
console.log(Object.keys(broken)); // ['[object Object]']
console.log(broken['[object Object]'].length); // 3Object.groupBy converts both role objects to the string '[object Object]', so every user ends up in one group. Map.groupBy keeps the objects as keys and compares them by reference.
Pitfall: Composite Keys Built Fresh Each Time
Because object keys are compared by reference, a callback that builds a new array or object for every item puts every item in its own group.
const sales = [
{ region: 'EU', year: 2025, amount: 100 },
{ region: 'EU', year: 2025, amount: 50 },
{ region: 'US', year: 2025, amount: 70 }
];
const wrong = Map.groupBy(sales, (s) => [s.region, s.year]);
console.log(wrong.size); // 3
const right = Map.groupBy(sales, (s) => `${s.region}|${s.year}`);
console.log(right.size); // 2
console.log(right.get('EU|2025').length); // 2Two arrays with the same contents are still different objects. Encode a composite key as a string, or look up a canonical object from a lookup table so that equal keys share one reference. Pick a separator that cannot appear inside the values.
Groups Hold References, Not Copies
The arrays inside the result are new, but the items in them are the original objects. Changing an item through a group changes it everywhere.
const tasks = [{ title: 'write', done: false }, { title: 'test', done: false }];
const byStatus = Map.groupBy(tasks, (t) => (t.done ? 'done' : 'open'));
byStatus.get('open')[0].done = true;
console.log(tasks[0].done); // trueThe grouping is also a snapshot. Changing done later does not move the task to another group. Call groupBy again when the data changes.
Aggregating After Grouping
Grouping is usually the first step. To get totals, counts, or averages, map over the entries and build a new Map.
const sales = [
{ region: 'EU', amount: 100 },
{ region: 'EU', amount: 50 },
{ region: 'US', amount: 70 }
];
const groups = Map.groupBy(sales, (s) => s.region);
const totals = new Map(
[...groups].map(([region, rows]) => [
region,
rows.reduce((sum, row) => sum + row.amount, 0)
])
);
console.log(totals.get('EU')); // 150
console.log(Object.fromEntries(totals)); // { EU: 150, US: 70 }If you only need counts or sums, a single loop that updates a Map directly avoids building the intermediate arrays. groupBy is the better choice when you need the items themselves.
Support and a Fallback
Map.groupBy is part of ES2024. It ships in Chrome and Edge 117, Firefox 119, Safari 17.4, and Node.js 21. For older runtimes, this function behaves the same way for normal use:
function groupBy(items, keyFn) {
const groups = new Map();
let index = 0;
for (const item of items) {
const key = keyFn(item, index++);
const group = groups.get(key);
if (group) {
group.push(item);
} else {
groups.set(key, [item]);
}
}
return groups;
}
console.log(groupBy(['ant', 'bee', 'cow'], (w) => w.length).get(3)); // ['ant', 'bee', 'cow']Prefer the built-in where it exists. Its behavior is defined by the specification, and anyone reading the code recognizes it right away.
Exercise
You have orders shaped like { customer: { id: 7 }, total: 20 }, where each order has its own customer object, even when two orders share an id. You call Map.groupBy(orders, (o) => o.customer) and get one group per order. Why, and what is the smallest fix?
Show answer
The key is the customer object. Keys are compared by reference, and every order holds a different object, so no two keys match. Group by a primitive instead: Map.groupBy(orders, (o) => o.customer.id). Orders with the same id then share one group.
Exercise
What does [...Map.groupBy([3, 8, 1, 6, 5], (n) => n > 4).entries()] produce, and in what order?
Show answer
[[false, [3, 1]], [true, [8, 6, 5]]]. The first item, 3, produces false, so the false key comes first. Each group lists its items in input order, and the keys stay booleans because a Map does not convert keys to strings.
Exercise
Write code that groups the words ['tree', 'apple', 'sky', 'about', 'tan'] by first letter, then prints a Map from each letter to the number of words in its group.
Show answer
const groups = Map.groupBy(['tree', 'apple', 'sky', 'about', 'tan'], (w) => w[0]); const counts = new Map([...groups].map(([letter, words]) => [letter, words.length])); console.log(counts); This logs Map(3) { 't' => 2, 'a' => 2, 's' => 1 }.