Sub topic 4
Writing Key Callbacks: Properties, Computed Keys, and Indexes
The callback you pass to Object.groupBy decides how your data is grouped. It runs once for each element and returns a key, and every element that gets the same key goes into the same group. This chapter covers the common kinds of key callback: reading a property, computing a label, combining several fields, and using the element's position.
This chapter assumes you know arrow functions, destructuring, template literals, and optional chaining with nullish coalescing (?. and ??). It also assumes you have seen a basic Object.groupBy call from the previous chapter.
The callback contract
Object.groupBy(items, callbackFn) calls callbackFn(element, index) for each element, in iteration order. Whatever the callback returns becomes a property key on the result object.
There are four rules to keep in mind:
- The callback receives exactly two arguments: the element and its index.
- It is called once per element, in order, and the calls are synchronous.
- Its return value is converted to a property key (a string or symbol). The next chapters cover that conversion in detail.
- If the callback throws,
groupBystops and rethrows the error. You get no partial result.
You can watch the call order directly:
const calls = [];
const groups = Object.groupBy(["x", "y", "z"], (value, index) => {
calls.push(`${index}:${value}`);
return index < 2 ? "first" : "rest";
});
console.log(calls); // ["0:x", "1:y", "2:z"]
console.log(groups.first); // ["x", "y"]
console.log(groups.rest); // ["z"]Grouping by a property
The most common callback reads one property. Destructuring in the parameter list keeps it short:
const orders = [
{ id: 1, customer: { country: "DE" }, total: 40 },
{ id: 2, customer: { country: "US" }, total: 15 },
{ id: 3, customer: { country: "DE" }, total: 72 },
{ id: 4, customer: { country: "FR" }, total: 9 },
];
const byCountry = Object.groupBy(orders, ({ customer }) => customer.country);
console.log(Object.keys(byCountry)); // ["DE", "US", "FR"]
console.log(byCountry.DE.map((o) => o.id)); // [1, 3]Nested properties work the same way, because the callback is ordinary code. You can write (o) => o.customer.country or destructure deeper with ({ customer: { country } }) => country.
Missing properties
If some elements lack the property, the callback returns undefined. That value is converted to the string "undefined", so those elements end up together under a key that is easy to miss:
const users = [
{ name: "Ana", team: "core" },
{ name: "Ben" },
{ name: "Cai", team: "web" },
{ name: "Dee", team: null },
];
const careless = Object.groupBy(users, (u) => u.team);
console.log(Object.keys(careless)); // ["core", "undefined", "web", "null"]
const careful = Object.groupBy(users, (u) => u.team ?? "unassigned");
console.log(Object.keys(careful)); // ["core", "unassigned", "web"]
console.log(careful.unassigned.map((u) => u.name)); // ["Ben", "Dee"]If the parent object can also be missing, chain the access: (o) => o.customer?.country ?? "unknown". Otherwise the callback throws a TypeError and the whole call fails.
Computed keys
The key does not have to exist in the data. The callback can run any logic and return a label.
Thresholds and buckets
const products = [
{ name: "pen", price: 3 },
{ name: "lamp", price: 24 },
{ name: "mug", price: 9 },
{ name: "chair", price: 89 },
{ name: "book", price: 27 },
];
const tierOf = ({ price }) => {
if (price < 10) return "budget";
if (price < 50) return "standard";
return "premium";
};
const byTier = Object.groupBy(products, tierOf);
console.log(byTier.budget.map((p) => p.name)); // ["pen", "mug"]
console.log(byTier.standard.map((p) => p.name)); // ["lamp", "book"]
console.log(byTier.premium.map((p) => p.name)); // ["chair"]
const byRange = Object.groupBy(products, ({ price }) => {
const low = Math.floor(price / 10) * 10;
return `${low}-${low + 9}`;
});
console.log(Object.keys(byRange)); // ["0-9", "20-29", "80-89"]Giving the callback a name, like tierOf above, makes it reusable and testable on its own. It also makes the grouping line read like a sentence.
Deriving keys from strings and dates
String operations make good keys. Grouping events by month only needs a slice of an ISO date:
const events = [
{ title: "Kickoff", date: "2026-01-14" },
{ title: "Review", date: "2026-02-03" },
{ title: "Retro", date: "2026-01-30" },
];
const byMonth = Object.groupBy(events, ({ date }) => date.slice(0, 7));
console.log(Object.keys(byMonth)); // ["2026-01", "2026-02"]
console.log(byMonth["2026-01"].map((e) => e.title)); // ["Kickoff", "Retro"]Normalize keys when the input is inconsistent. (w) => w[0].toLowerCase() puts "Apple" and "avocado" in the same group. Without toLowerCase(), they land in separate groups.
Composite keys
To group by more than one field, join the fields into one string, using a separator that cannot appear in the values:
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 byTypeAndStock = Object.groupBy(
inventory,
({ type, quantity }) => `${type}|${quantity > 0 ? "in" : "out"}`
);
console.log(Object.keys(byTypeAndStock));
// ["vegetables|in", "fruit|out", "meat|in", "fruit|in"]
const [type, stock] = "fruit|in".split("|");
console.log(type, stock); // "fruit" "in"The result is flat: one level of groups, each named by the combined key. If you want nested groups instead, such as type first and then stock, group by type and then group each type's array again. The chapter on transforming groups shows that pattern.
Using the index
The second argument is the element's position in iteration order, starting at 0. Keys based on the index group elements by where they are, not by what they contain.
Chunking into pages
const items = ["a", "b", "c", "d", "e"];
const pageSize = 2;
const pages = Object.groupBy(
items,
(_, index) => `page${Math.floor(index / pageSize) + 1}`
);
console.log(pages.page1); // ["a", "b"]
console.log(pages.page2); // ["c", "d"]
console.log(pages.page3); // ["e"]The underscore is a common name for a parameter you don't use. You still have to declare it, because the index is the second argument.
Round-robin distribution
const tasks = ["t1", "t2", "t3", "t4", "t5", "t6", "t7"];
const workers = ["alpha", "beta", "gamma"];
const assigned = Object.groupBy(tasks, (_, i) => workers[i % workers.length]);
console.log(assigned.alpha); // ["t1", "t4", "t7"]
console.log(assigned.beta); // ["t2", "t5"]
console.log(assigned.gamma); // ["t3", "t6"]There is no third argument
Callbacks for map, filter, and reduce receive the whole array as a third argument. The groupBy callback does not, because groupBy accepts any iterable, and many iterables are not arrays:
const result = Object.groupBy([1, 2, 3], (n, i, arr) => typeof arr);
console.log(Object.keys(result)); // ["undefined"]If the key depends on the whole collection, such as "above or below average", compute that value before the call and read it inside the callback:
const scores = [55, 90, 72, 40, 88];
const average = scores.reduce((sum, s) => sum + s, 0) / scores.length; // 69
const split = Object.groupBy(scores, (s) => (s >= average ? "above" : "below"));
console.log(split.above); // [90, 72, 88]
console.log(split.below); // [55, 40]Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Property missing on some elements | An unexpected "undefined" group | Return `value ?? "fallback"` |
| Reading a nested property of a missing object | `TypeError`, and no result | Use `?.` in the callback |
| Using the third `array` argument | `arr` is `undefined` | Compute collection-wide values beforehand |
| Inconsistent casing or whitespace | Near-duplicate groups like "Fruit" and "fruit" | Normalize with `trim()` and `toLowerCase()` |
| Mutating elements inside the callback | Source data changes as a side effect | Keep the callback pure: read, don't write |
| Returning an object as the key | Everything lands under "[object Object]" | Return a string, or use `Map.groupBy` |
The last row in the table points ahead. When you need an actual object as a key, Object.groupBy is the wrong tool, and a later chapter on Map.groupBy explains why.
Exercise
Given const logs = [{ level: "error" }, { level: "WARN" }, {}, { level: "Error" }], write an Object.groupBy call that produces exactly the keys "error", "warn", and "none", with both error entries in the same group.
Show answer
Object.groupBy(logs, (log) => log.level?.toLowerCase() ?? "none"). Optional chaining returns undefined for the entry with no level, ?? turns that into "none", and toLowerCase() merges "error" and "Error". The keys come out in first-seen order: ["error", "warn", "none"].
Exercise
You have an array of 10 numbers and want them in groups of 3 by position: "g0" for indexes 0–2, "g1" for 3–5, and so on. What callback do you write, and how many elements does the last group hold?
Show answer
(_, i) => g${Math.floor(i / 3)}. Indexes 9 and above map to "g3", so the last group holds one element, the number at index 9.
Exercise
A teammate writes Object.groupBy(values, (v, i, all) => (v > Math.max(...all) / 2 ? "high" : "low")). It throws a TypeError. Why, and how do you fix it?
Show answer
The groupBy callback receives only the element and the index, so all is undefined, and spreading undefined throws a TypeError. Compute the threshold first, for example const half = Math.max(...values) / 2, then use (v) => (v > half ? "high" : "low").