Sub topic 1
What Grouping Means and Why It Comes Up So Often
Grouping is one of the most common data operations in application code, and one of the easiest to get subtly wrong. This chapter defines the operation, shows where it comes up in everyday JavaScript work, and explains why the obvious approaches break down. The rest of the tutorial builds on this foundation: first the older reduce-based approach, then Object.groupBy and Map.groupBy, which were added in ES2024.
Prerequisites
This tutorial assumes you can already work with the following without explanation:
- JavaScript arrays and array methods such as
map,filter, andreduce - Arrow functions and destructuring, for example
({ type }) => type - Plain objects and property access with dot and bracket notation
- Basic use of
Map:new Map(),get,set, andhas - Optional chaining (
?.) and nullish coalescing (??)
You also need a runtime to run the examples. Any current browser console or Node.js 18 or later is enough for the code in this chapter, because it uses no grouping built-ins yet.
The Operation Itself
To group a collection, you assign every element a key and collect the elements that share a key into the same bucket. The result maps each key to the list of elements that produced it.
Take a list of orders:
const orders = [
{ id: 1, status: "shipped", total: 40 },
{ id: 2, status: "pending", total: 15 },
{ id: 3, status: "shipped", total: 22 },
{ id: 4, status: "cancelled", total: 9 },
{ id: 5, status: "refunded", total: 30 },
];Grouping these by status produces this shape:
const ordersByStatus = {
shipped: [
{ id: 1, status: "shipped", total: 40 },
{ id: 3, status: "shipped", total: 22 },
],
pending: [{ id: 2, status: "pending", total: 15 }],
cancelled: [{ id: 4, status: "cancelled", total: 9 }],
refunded: [{ id: 5, status: "refunded", total: 30 }],
};
console.log(Object.keys(ordersByStatus)); // ["shipped", "pending", "cancelled", "refunded"]
console.log(ordersByStatus.shipped.length); // 2The function that decides each element's key is the key function. Here it reads one property, order.status. It could just as easily compute a value, such as order.total > 20 ? "large" : "small". The key function is the only part that changes from one grouping task to the next. The bucketing logic around it stays the same.
The Rules a Correct Grouping Follows
Any correct grouping, however it is implemented, meets four rules. Knowing them helps you spot bugs in hand-written code and predict how the built-in methods behave.
- Every element lands in exactly one group. No element is dropped and none is duplicated. The group sizes add up to the input length.
- Groups exist only for keys that occur. If no order is
"returned", the result has noreturnedkey. You do not get empty arrays for keys you never saw. - Order within a group follows the input. Orders 1 and 3 appear in that order inside
shippedbecause that is their order in the source array. - Keys are discovered from the data. You do not need to list the possible keys in advance. A new status value in tomorrow's data produces a new group automatically.
Rule 2 has a practical consequence. If your UI always shows a "Returned" column, you have to supply the empty default yourself, for example with groups.returned ?? []. Rule 4 is what separates grouping from a fixed set of filters, as the next section shows.
How Grouping Differs from Other Array Operations
Grouping looks like several familiar operations but does a different job from each of them.
| Operation | Input | Output | Elements kept |
|---|---|---|---|
| `map` | array of n items | array of n transformed items | all, transformed |
| `filter` | array plus one predicate | one array | only matches; the rest are discarded |
| `sort` | array plus comparator | same items, reordered | all, in one flat list |
| `find` | array plus predicate | one item or `undefined` | at most one |
| grouping | iterable plus key function | key to array of items | all, split into buckets |
Some related operations get confused with grouping:
- Partitioning is grouping with exactly two keys, usually
trueandfalse, or names such as"pass"and"fail". It is a special case of grouping, not a separate tool. - Indexing, sometimes called "key by", maps each key to a single element, such as users by
id. If two elements share a key, indexing keeps only one of them. Grouping keeps both. Use indexing when keys are unique by design. - Counting maps each key to a number instead of an array. You can count by grouping and then measuring each bucket, which a later chapter covers.
Where Grouping Shows Up
Grouping comes up any time data arrives as a flat list but people need to look at it in sections:
- Interfaces: messages by day, contacts by first letter, products by category, tasks by assignee or column on a board.
- Reports: sales by region, errors by HTTP status code, sign-ups by month. These usually become sums or counts after the grouping step.
- Batching: splitting jobs by target API or shard so each batch can be sent in one request.
- Validation and cleanup: finding duplicate emails by grouping on the normalized address and keeping groups with more than one entry.
- Log analysis: bucketing entries by severity, service name, or a time window computed from a timestamp.
In each case the data arrives flat and the result needs to be keyed. The key may be a stored field or a computed value such as a date string or a size bucket.
Why the Obvious Approach Fails
The first approach many developers reach for is one filter call per key:
const orders = [
{ id: 1, status: "shipped", total: 40 },
{ id: 2, status: "pending", total: 15 },
{ id: 3, status: "shipped", total: 22 },
{ id: 4, status: "cancelled", total: 9 },
{ id: 5, status: "refunded", total: 30 },
];
const shipped = orders.filter((o) => o.status === "shipped");
const pending = orders.filter((o) => o.status === "pending");
const cancelled = orders.filter((o) => o.status === "cancelled");
const accountedFor = shipped.length + pending.length + cancelled.length;
console.log(accountedFor, "of", orders.length); // 3 of 5? No: 4 of 5
console.log(accountedFor === orders.length); // falseThe refunded order went missing, and nothing reported an error. The code breaks rule 4 because it hard-codes the keys, and as a result it also breaks rule 1. It has two other costs:
- Repeated passes. With k keys, the code scans the array k times. That is fine for 5 items and 3 keys. It gets expensive for 50,000 log lines and 40 service names.
- Duplicated logic. The key expression
o.statusis repeated in every filter. If the key changes, say too.status.toLowerCase(), every copy must change too, and missing one creates a quiet mismatch.
A real grouping makes one pass, calls the key function once per element, and creates buckets as new keys appear.
Checking a Grouping Against the Rules
When you write grouping code by hand or refactor it, a small checker can confirm that the rules hold. The function below accepts any object of arrays, so you can run it on the output of every technique in this tutorial.
function checkGrouping(items, groups, keyFn) {
const problems = [];
const seen = new Set();
for (const [key, bucket] of Object.entries(groups)) {
if (bucket.length === 0) problems.push(`empty group: ${key}`);
let lastIndex = -1;
for (const item of bucket) {
const index = items.indexOf(item);
if (index === -1) problems.push(`unknown item in ${key}`);
if (seen.has(item)) problems.push(`duplicate item in ${key}`);
if (String(keyFn(item)) !== key) problems.push(`wrong group: ${key}`);
if (index < lastIndex) problems.push(`out of order in ${key}`);
seen.add(item);
lastIndex = index;
}
}
for (const item of items) {
if (!seen.has(item)) problems.push(`missing item: ${JSON.stringify(item)}`);
}
return problems;
}
const orders = [
{ id: 1, status: "shipped", total: 40 },
{ id: 2, status: "pending", total: 15 },
{ id: 3, status: "shipped", total: 22 },
{ id: 4, status: "cancelled", total: 9 },
{ id: 5, status: "refunded", total: 30 },
];
const filtered = {
shipped: orders.filter((o) => o.status === "shipped"),
pending: orders.filter((o) => o.status === "pending"),
cancelled: orders.filter((o) => o.status === "cancelled"),
};
console.log(checkGrouping(orders, filtered, (o) => o.status));
// ['missing item: {"id":5,"status":"refunded","total":30}']The checker compares items by reference with indexOf and Set, which matches how real grouping works: buckets hold the original elements, not copies. It also converts each key with String(...), because plain-object property names are strings. That conversion matters a great deal once keys are numbers, booleans, or objects. Later chapters cover it in detail and show when a Map result is the better choice.
Questions to Ask Before You Group
Answer these before you write any grouping code, because each answer affects which tool fits best:
- What is the key? A stored property, a computed value, or something that depends on the element's position?
- What type is the key? Strings work naturally as object properties. Numbers, booleans, dates, and objects need more care.
- Do you need fixed groups? If downstream code expects every category to exist, plan to fill in defaults for empty ones.
- Does group order matter? Rendering sections in a particular order may require sorting the keys yourself.
- What happens after grouping? If you only need counts or totals, grouping is an intermediate step, and the shape of the final summary should guide your choice.
Exercise
A teammate groups support tickets into urgent and normal lists with tickets.filter(t => t.priority >= 3) and tickets.filter(t => t.priority >= 1). Which grouping rule does this break, and what single key function would fix it?
Show answer
It breaks rule 1 (every element in exactly one group). A ticket with priority 3 or higher matches both predicates and appears in both lists. A ticket with priority 0 matches neither and disappears. A single key function such as t => (t.priority >= 3 ? "urgent" : "normal") returns exactly one key per ticket, so every ticket lands in one bucket.
Exercise
For each task, say whether it calls for grouping, indexing, or filtering: (a) look up a user record by its unique id; (b) list all invoices per customer; (c) show only overdue invoices.
Show answer
(a) Indexing, because each id maps to exactly one record. (b) Grouping, because each customer can have many invoices and all of them must be kept. (c) Filtering, because one predicate keeps the matches and nothing else is needed.
Exercise
Grouping 200 orders by status produces groups whose lengths add up to 197. Without looking at the code, what can you conclude?
Show answer
Rule 1 is broken: three orders were dropped. The most likely cause is that the code hard-codes the list of keys, as the filter-per-key approach does, and the three orders have a status that is not on the list. A real one-pass grouping discovers keys from the data and cannot drop elements.