Sub topic 3
Your First Object.groupBy Call
This chapter assumes you know arrays and reduce, arrow functions with destructuring, and plain objects. It also builds on the previous chapter's hand-written reduce grouping. Here you will make a first Object.groupBy call, learn the shape of its result, and see the step-by-step process it follows. You will also meet the mistakes people make most often on their first try.
The Signature
Object.groupBy is a static method. You call it on the Object constructor itself, not on an array:
Object.groupBy(items, callbackFn);| Parameter | What it is |
|---|---|
| `items` | Any iterable: an array, string, Set, Map, generator, and so on |
| `callbackFn` | A function called once per element. It returns the key of the group the element belongs to |
| Return value | A new object with one property per distinct key. Each value is an array of the elements that produced that key |
The method was added in ES2024. It does not change items. Every call returns a fresh object holding fresh arrays.
A First Example
Here is the inventory data used throughout this tutorial, grouped by each item's type:
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(Object.keys(byType)); // ["vegetables", "fruit", "meat"]
console.log(byType.fruit.map((item) => item.name)); // ["bananas", "cherries"]The callback ({ type }) => type destructures each element and returns its type string. That string becomes a property name on the result. Conceptually, the result looks like this:
{
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 }],
}Compare this with the reduce version from the previous chapter. That version needed an accumulator, an "does this group exist yet?" check, a push, and a return acc. All of that bookkeeping now lives inside the built-in method. You write only the part that matters: how to pick a key.
What Happens Inside
The specification defines a simple loop. Knowing it lets you predict the result of any call without running it.
- Check that
itemsis notnullorundefined, and thatcallbackFnis callable. If either check fails, throw aTypeError. - Get an iterator from
items. - For each element, call
callbackFn(element, index). The index starts at 0. - Convert the returned value to a property key.
- If a group with that key exists, append the element to it. If not, create a new group containing just this element.
- When the iterator is done, build an object with no prototype. Then add one property per group, in the order the groups were first created.
Several guarantees follow from this loop:
- Every element lands in exactly one group. Nothing is dropped or duplicated.
- The callback runs once per element, in iteration order. It never runs twice for the same element, and it does not run ahead of time.
- Elements keep their original relative order inside each group. Bananas came before cherries in the input, so they come first in
byType.fruit. - There are no empty groups. A key exists only because some element produced it.
- Empty input gives an empty object.
Object.groupBy([], fn)returns an object with no properties and never callsfn.
You can see the call order for yourself:
const calls = [];
const grouped = Object.groupBy(["x", "y", "x"], (value, index) => {
calls.push(`${index}:${value}`);
return value;
});
console.log(calls); // ["0:x", "1:y", "2:x"]
console.log(grouped.x); // ["x", "x"]
console.log(grouped.y); // ["y"]If the callback throws, the error propagates out of Object.groupBy and no result is returned. You never get a half-built object.
Reading the Result
Groups are ordinary arrays, so every array method works on them:
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.length); // 2
console.log(byType["vegetables"][0].name); // "asparagus"
for (const [type, items] of Object.entries(byType)) {
console.log(`${type}: ${items.length}`);
}
// vegetables: 1
// fruit: 2
// meat: 1Because empty groups don't exist, reading a key that no element produced gives undefined, not an empty array. Code that assumes a group is present will break on input that lacks it:
const byType = Object.groupBy([{ type: "fruit" }], ({ type }) => type);
console.log(byType.meat); // undefined
console.log(byType.meat?.length ?? 0); // 0
// byType.meat.length would throw a TypeErrorJSON.stringify also works fine on the result, which helps when you want compact log output or need to send grouped data over the network:
const grouped = Object.groupBy([1, 2, 3], (n) => (n % 2 ? "odd" : "even"));
console.log(JSON.stringify(grouped)); // {"odd":[1,3],"even":[2]}Common First-Call Mistakes
Calling It on the Array
The method is not on Array.prototype, so this throws:
const inventory = [{ type: "fruit" }];
try {
inventory.groupBy(({ type }) => type);
} catch (error) {
console.log(error instanceof TypeError); // true
// inventory.groupBy is not a function
}
const ok = Object.groupBy(inventory, ({ type }) => type);
console.log(Object.keys(ok)); // ["fruit"]The final chapter explains why the language designers made it static.
Forgetting to Return the Key
An arrow function with a braced body returns undefined unless you write return. Every element then lands in a single group named "undefined":
const items = [{ type: "fruit" }, { type: "meat" }];
const wrong = Object.groupBy(items, ({ type }) => {
type; // no return
});
console.log(Object.keys(wrong)); // ["undefined"]
console.log(wrong.undefined.length); // 2
const right = Object.groupBy(items, ({ type }) => {
return type;
});
console.log(Object.keys(right)); // ["fruit", "meat"]If every element ends up in one group, check your callback's return value first.
Passing a Plain Object as Input
Plain objects are not iterable, so they can't be grouped directly. Convert the object first with Object.values or Object.entries:
const stock = { apples: 4, pears: 0, plums: 9 };
try {
Object.groupBy(stock, (n) => n);
} catch (error) {
console.log(error instanceof TypeError); // true
}
const byAvailability = Object.groupBy(
Object.entries(stock),
([, count]) => (count > 0 ? "inStock" : "soldOut")
);
console.log(byAvailability.soldOut); // [["pears", 0]]
console.log(byAvailability.inStock.map(([name]) => name)); // ["apples", "plums"]Passing Something That Is Not a Function
Object.groupBy(items, "type") throws a TypeError. The method has no property-name shorthand. You must always pass a function. Object.groupBy(null, fn) and Object.groupBy(undefined, fn) throw too, so guard against missing data before you call it, for example with Object.groupBy(data ?? [], fn).
Summary of Behaviors
| Situation | Result |
|---|---|
| Empty input | Empty null-prototype object; callback never runs |
| Key produced by no element | Property is absent (`undefined`) |
| Callback returns `undefined` | Group stored under the key `"undefined"` |
| Callback throws | Error propagates; nothing is returned |
| `items` is `null`, `undefined`, or not iterable | `TypeError` |
| `callbackFn` is not callable | `TypeError` |
| Order inside a group | Same as the input order |
The next chapter looks more closely at the callback: computing keys from logic and using the index argument.
Exercise
What does this print, and why? const r = Object.groupBy(["apple", "avocado", "banana"], (w) => { w[0]; }); console.log(Object.keys(r), r.a);
Show answer
It prints ["undefined"] and undefined. The braced arrow body has no return statement, so every call returns undefined, and all three words go into a single group under the key "undefined". No element produced the key "a", so r.a is undefined. Writing (w) => w[0] fixes it, giving keys ["a", "b"] with r.a equal to ["apple", "avocado"].
Exercise
Given const orders = [{ id: 1, status: "paid" }, { id: 2, status: "pending" }, { id: 3, status: "paid" }], group the orders by status, then safely log how many orders are "refunded" (expected: 0) and the ids of the paid orders in input order.
Show answer
const byStatus = Object.groupBy(orders, ({ status }) => status); console.log(byStatus.refunded?.length ?? 0); console.log(byStatus.paid.map((o) => o.id)); This prints 0 and [1, 3]. No order produced the key "refunded", so that group is absent, and optional chaining with ?? 0 avoids a TypeError. Groups keep the input order, so ids 1 and 3 come out in that order.
Exercise
You have const scores = { ana: 91, ben: 58, cy: 74 }. Why does Object.groupBy(scores, (s) => (s >= 60 ? "pass" : "fail")) fail, and how do you get an object with the names that passed and failed?
Show answer
A plain object is not iterable, so Object.groupBy throws a TypeError when it tries to get an iterator. Group its entries instead: const g = Object.groupBy(Object.entries(scores), ([, s]) => (s >= 60 ? "pass" : "fail")); then g.pass.map(([name]) => name) gives ["ana", "cy"] and g.fail.map(([name]) => name) gives ["ben"].