Sub topic 4
Writing Key Callbacks: Properties, Computed Keys, and Indexes
This chapter assumes you know arrow functions, destructuring, and the basic Object.groupBy(items, callback) call from the previous chapter. Here the focus is the callback. It is the one piece of logic you write, and it decides every group.
What the Callback Receives and Returns
Object.groupBy calls your callback once for each element, in order. It passes two arguments:
| Argument | Meaning |
|---|---|
| `element` | The current item from the iterable |
| `index` | The zero-based position of that item |
The callback's return value is the group key. Elements that return the same key end up in the same array.
Reading a Property
The most common callback reads a field. Destructuring in the parameter list keeps it short:
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.meat.map((item) => item.name)); // ["goat"]Computing a Key
The key does not have to exist on the element. You can return any value you compute. A ternary works well for sorting items into buckets:
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); // 3
console.log(byStock.ok.map((item) => item.name)); // ["goat"]With more than two buckets, use a small function with if statements or a lookup table. Keep the callback pure: it should depend only on its arguments and should not change the element.
Using the Index
The second argument lets you group by position instead of by content. A common use is splitting an array into chunks of a fixed size:
const letters = ["a", "b", "c", "d", "e"];
const chunks = Object.groupBy(letters, (_, index) => Math.floor(index / 2));
console.log(chunks[1]); // ["c", "d"]
console.log(Object.values(chunks)); // [["a", "b"], ["c", "d"], ["e"]]The underscore marks the unused element parameter. The numeric keys 0, 1, 2 are stored as strings. A later chapter covers that conversion in detail.
Common Mistakes
The most frequent bug is an arrow function with a block body and no return:
const inventory = [
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
];
const wrong = Object.groupBy(inventory, (item) => {
item.type; // no return, so the callback returns undefined
});
console.log(Object.keys(wrong)); // ["undefined"]Every element lands under the key "undefined". If you see that key, check your callback for a missing return.
Two more things to watch for:
- Inconsistent keys.
"Fruit"and"fruit"are different keys. Normalize withtoLowerCase()ortrim()inside the callback. - Expensive work. The callback runs once per element. Do any costly setup, such as building a lookup table, before calling
groupBy.
Exercise
Given const words = ["Apple", "avocado", "Banana", "blueberry", "cherry"], write an Object.groupBy call that groups the words by first letter, ignoring case, so that the result has the keys "a", "b", and "c".
Show answer
const byLetter = Object.groupBy(words, (word) => word[0].toLowerCase()); This gives { a: ["Apple", "avocado"], b: ["Banana", "blueberry"], c: ["cherry"] }. Without toLowerCase(), "A" and "a" would form separate groups.
Exercise
What does Object.groupBy([10, 20, 30, 40], (n, i) => (i < 2 ? "first" : "rest")) return?
Show answer
{ first: [10, 20], rest: [30, 40] }. The callback ignores the values and uses only the index. Indexes 0 and 1 go to "first", and indexes 2 and 3 go to "rest".