Sub topic 1
What Grouping Means and Why It Comes Up So Often
Grouping splits a list into buckets that share a key. Common examples are orders by status, log lines by level, and products by category. You do this whenever you build a report, a sectioned UI list, or a lookup table.
Prerequisites
This chapter assumes you know:
- Array methods such as
map,filter, andreduce - Arrow functions and destructuring
- Plain objects and property access
- Optional chaining (
?.) and nullish coalescing (??,??=)
The Old Way: Grouping with reduce
Before ES2024, most code grouped with reduce:
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 },
];
const byType = inventory.reduce((acc, item) => {
(acc[item.type] ??= []).push(item);
return acc;
}, {});
console.log(Object.keys(byType)); // ["vegetables", "fruit", "meat"]This works, but it is easy to get wrong. People forget return acc or the initial {}. A key like "constructor" also collides with Object.prototype.
Your First Object.groupBy Call
Object.groupBy(items, callback) calls the callback once for each element. It collects the elements that return the same key into an array stored under that key:
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 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
console.log(byType.fruit.map((item) => item.name)); // ["bananas", "cherries"]Writing Key Callbacks: Properties, Computed Keys, and Indexes
The key does not have to be an existing property. Any logic that returns a key works:
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 },
];
const byStock = Object.groupBy(inventory, ({ quantity }) =>
quantity > 5 ? "ok" : "restock"
);
console.log(byStock.restock.length); // 3The callback also receives the element's index as its second argument. You can write it as (item, index) => ....
Working with a Null-Prototype Result
The result object has a null prototype, so it inherits no methods. Calling groups.hasOwnProperty(...) throws a TypeError. Use these checks instead:
const groups = Object.groupBy([1, 2, 3], (n) => (n > 1 ? "big" : "small"));
console.log(Object.getPrototypeOf(groups)); // null
console.log(Object.hasOwn(groups, "big")); // true
console.log("medium" in groups); // false
console.log(groups.medium?.length ?? 0); // 0Exercise
Group the numbers [3, 8, 12, 5] with Object.groupBy into "low" (under 10) and "high". Then safely print how many "medium" values there are.
Show answer
const g = Object.groupBy([3, 8, 12, 5], (n) => (n < 10 ? "low" : "high")); console.log(g.low); // [3, 8, 5] console.log(g.medium?.length ?? 0); // 0