Sub topic 9
Choosing Between Object.groupBy and Map.groupBy
This chapter assumes you already know how Object.groupBy and Map.groupBy work, how Object.groupBy converts keys to strings, and why its result has a null prototype. Here we turn those facts into a decision you can make quickly.
The Core Question: What Type Are Your Keys?
Both methods call your key callback once per element and collect elements into arrays. They differ in what happens to the key the callback returns.
Object.groupByturns each key into a property key. Anything that is not a symbol becomes a string, sotruebecomes"true",42becomes"42", and every plain object becomes"[object Object]".Map.groupBystores each key exactly as returned and compares keys with SameValueZero. Objects are matched by reference, and numbers stay numbers.
If your keys are already strings, such as a status, a category name, or a first letter, either method works. If the key's type or identity matters, use Map.groupBy.
Seeing the Difference on One Dataset
const alice = { name: "Alice" };
const bob = { name: "Bob" };
const orders = [
{ id: 1, customer: alice, status: "paid" },
{ id: 2, customer: bob, status: "pending" },
{ id: 3, customer: alice, status: "pending" },
];
// String keys: Object.groupBy is the natural fit
const byStatus = Object.groupBy(orders, (o) => o.status);
console.log(byStatus.pending.length); // 2
console.log(JSON.stringify(Object.keys(byStatus))); // ["paid","pending"]
// Object keys: Map.groupBy keeps each customer distinct
const byCustomer = Map.groupBy(orders, (o) => o.customer);
console.log(byCustomer.get(alice).map((o) => o.id)); // [1, 3]
console.log(byCustomer.size); // 2
// The same object keys with Object.groupBy collapse into one group
const broken = Object.groupBy(orders, (o) => o.customer);
console.log(Object.keys(broken)); // ["[object Object]"]
console.log(broken["[object Object]"].length); // 3The last grouping throws no error. It just puts every order into a single group, which is why it is easy to miss.
Other Factors That Tip the Decision
| Concern | Object.groupBy | Map.groupBy |
|---|---|---|
| Key types kept | Strings and symbols only | Any value |
| Reading a group | `groups.fruit` or `groups[key]` | `groups.get(key)` |
| Checking a group exists | `Object.hasOwn(groups, key)` or `key in groups` | `groups.has(key)` |
| Counting groups | `Object.keys(groups).length` | `groups.size` |
| Key order | Integer-like keys first, then insertion order | Always insertion order |
| `JSON.stringify` | Works directly | Produces `"{}"` |
| Destructuring | `const { paid, pending } = groups` | Not supported |
Use Object.groupBy when the result goes into JSON, gets destructured, or is passed to code that expects a plain object. Use Map.groupBy when keys are numbers you will do math on, booleans you want to look up as booleans, dates, or object references, or when the order of groups must follow insertion order exactly.
A Decision Flow
Exercises
Exercise
You group log entries by HTTP status code (200, 404, 500) and then want to sum the codes of the groups that exist, using the keys as numbers. Which method should you use, and why?
Show answer
Map.groupBy. Object.groupBy would turn each code into a string such as "404", so you would have to convert the keys back to numbers before doing math. Map.groupBy keeps them as numbers, so [...map.keys()] can be summed directly.
Exercise
An API handler groups products by category name and returns the result with res.json(groups). Which method fits better?
Show answer
Object.groupBy. The keys are already strings, and JSON.stringify serializes the plain object correctly. A Map would serialize as an empty object "{}" unless you converted it first.