Sub topic 1
What Grouping Means and Why It Comes Up So Often
Grouping takes a flat list of items and sorts them into buckets. Every item in a bucket shares a key. You choose what the key is. It might be a category name, a date, a status, or a value you calculate. This chapter defines the problem and shows the shape of the result. Later chapters cover the code that produces it.
Prerequisites
This tutorial assumes you are comfortable with:
- JavaScript arrays and array methods such as
map,filter, andreduce - Arrow functions and destructuring
- Plain objects and property access
- Basic use of
Map - Optional chaining (
?.) and nullish coalescing (??)
The shape of the problem
Here is a small inventory list:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];Suppose you want the items organized by type. The result you want looks like this:
const grouped = {
vegetables: [{ name: "asparagus", type: "vegetables", quantity: 5 }],
fruit: [
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 },
],
meat: [{ name: "goat", type: "meat", quantity: 23 }],
};
console.log(Object.keys(grouped)); // ["vegetables", "fruit", "meat"]
console.log(grouped.fruit.length); // 2The result has three properties:
- Each key appears once, even when many items share it.
- Each group is an array, even when it holds a single item.
- Items stay in their original order inside each group.
Why grouping comes up so often
Data usually arrives as a flat list from an API, a database query, or a CSV file. Interfaces and reports usually want it in sections. Common cases include:
| Task | Key |
|---|---|
| Show orders under status headings | `order.status` |
| Build a calendar of events | the event's date string |
| Show contacts in an A–Z list | first letter of the name |
| Flag low stock | `quantity < 6 ? "restock" : "ok"` |
| Count errors by HTTP code | `response.status` |
The last two rows matter. The key does not have to be a stored property. It can be any value you compute from the item. Grouping is often the first step before another operation, such as counting each bucket, summing a field, or rendering one section per key.
What makes grouping awkward
For years JavaScript had no built-in grouping method. filter returns one subset per call, so grouping into three buckets took three passes, and you had to know the keys in advance. Developers wrote the logic by hand instead: start an empty object, loop over the items, create an array the first time each key appears, then push into it. The idea is easy, but the code is easy to get subtly wrong. One common bug is forgetting to create the array before pushing. Another is choosing a key such as "constructor" that clashes with properties inherited from Object.prototype.
ES2024 added two static methods for this job. Object.groupBy returns a plain object keyed by strings. Map.groupBy returns a Map whose keys can be any value. Before covering them, the next chapter looks at the hand-written reduce version so you can see what the new methods replace.
Exercise
You have an array of log entries, each shaped like { level: "error", message: "..." }. You want one section per level, with entries in their original order. What is the key, what does each group contain, and how many groups appear if the levels are "info", "error", "info", "warn"?
Show answer
The key is entry.level. Each group is an array of the full log entry objects for that level, in their original order. Three groups appear: "info" (two entries), "error" (one entry), and "warn" (one entry).
Exercise
Why can't a single call to filter do the work of grouping?
Show answer
filter returns one subset based on a yes/no test. Grouping produces many subsets at once, one per distinct key, and you may not know the keys in advance.