Sub topic 12
Groups Share Element References
This chapter assumes you already know how to call Object.groupBy and Map.groupBy, and that you understand the difference between primitive values and objects in JavaScript. In particular, you should know that assigning an object to a variable copies a reference to it, not the object itself.
When you group an array, you get a new container with new arrays inside it. The elements in those arrays are not new. Every group holds the same element references as the source iterable. That is usually what you want, because grouping stays fast and cheap. It does mean that changing an object through a group also changes it everywhere else it is referenced.
What Is New and What Is Shared
Both Object.groupBy and Map.groupBy create three kinds of things:
- A result container: a null-prototype object or a
Map. - One fresh array per group.
- Entries in those arrays that point to the original elements.
Only the first two are new. The groupBy methods never clone elements. They push each value they receive from the iterator straight into its group's array.
const people = [{ name: "Ana" }, { name: "Ben" }];
const byInitial = Object.groupBy(people, (p) => p.name[0]);
byInitial.A[0].name = "Anna";
console.log(people[0].name); // "Anna"
console.log(byInitial.A[0] === people[0]); // trueThe strict equality check returns true because byInitial.A[0] and people[0] are the same object. There is only one object in memory with two paths leading to it.
The Group Arrays Themselves Are Independent
The arrays in the result are new, so changing an array's structure does not touch the source. You can push, pop, splice, or sort a group array and the original array stays as it was.
const scores = [
{ name: "Ana", team: "red", points: 3 },
{ name: "Ben", team: "blue", points: 7 },
{ name: "Cy", team: "red", points: 8 },
];
const byTeam = Object.groupBy(scores, (s) => s.team);
byTeam.red.push({ name: "Zoe", team: "red", points: 9 });
console.log(scores.length); // 3
byTeam.red.sort((a, b) => b.points - a.points);
console.log(byTeam.red.map((s) => s.name)); // ["Zoe", "Cy", "Ana"]
console.log(scores.map((s) => s.name)); // ["Ana", "Ben", "Cy"]The rule is simple. Operations on the array are local to the group. Operations on an element are visible to everyone holding that element.
| Operation | Affects source? | Why |
|---|---|---|
| `group.push(x)` / `group.splice(...)` | No | The group array is a new array |
| `group.sort(...)` / `group.reverse()` | No | Reorders only the new array |
| `group[0] = other` | No | Replaces a slot in the new array |
| `group[0].prop = value` | Yes | Mutates the shared element |
| `group[0].list.push(x)` | Yes | Mutates an object nested in the shared element |
| `source.push(x)` after grouping | No | Groups are a snapshot of membership |
Primitives Are Safe
When the elements are primitives such as numbers, strings, or booleans, there is nothing to share. Primitives are immutable, and assigning a new value to a slot only changes that slot.
const nums = [1, 2, 3, 4];
const parity = Object.groupBy(nums, (n) => (n % 2 ? "odd" : "even"));
parity.odd[0] = 100;
console.log(nums); // [1, 2, 3, 4]
console.log(parity.odd); // [100, 3]The reference issue only applies when elements are objects, arrays, functions, or other reference types.
Grouping Is a Snapshot of Membership, Not a Live View
Grouping decides which group each element goes into once, at the moment you call the method. If an element later changes in a way that would give it a different key, it stays in its old group. If the source array gains new elements, the groups do not update.
const tasks = [
{ id: 1, status: "todo" },
{ id: 2, status: "done" },
];
const byStatus = Object.groupBy(tasks, (t) => t.status);
tasks[0].status = "done";
console.log(byStatus.todo[0].status); // "done" (but it is still in the todo group)
console.log(byStatus.done.length); // 1
tasks.push({ id: 3, status: "todo" });
console.log(byStatus.todo.length); // 1This combination is a common source of bugs. The element's data is live because it is shared, but its group membership is frozen. After tasks[0].status = "done", the todo group contains a task whose status says "done". The grouped result now contradicts itself.
The same applies to Map.groupBy, and it applies across calls. If you group one array with both methods, both results point to the same element objects:
const items = [{ id: 1, tag: "a" }];
const asObject = Object.groupBy(items, (i) => i.tag);
const asMap = Map.groupBy(items, (i) => i.tag);
console.log(asObject.a[0] === asMap.get("a")[0]); // trueGetting Independent Copies When You Need Them
Sometimes you want to edit grouped data without touching the source, for example to build a draft version of a form or to apply a "what if" calculation. In that case, copy the elements yourself, either before grouping or afterward.
A shallow copy with spread syntax creates new top-level objects, but nested objects and arrays are still shared. A deep copy with structuredClone (available in modern browsers and Node.js 17+) copies everything that can be cloned.
const orders = [
{ id: 1, region: "EU", items: ["pen"] },
{ id: 2, region: "US", items: ["ink"] },
];
const shallow = Object.groupBy(
orders.map((o) => ({ ...o })),
(o) => o.region
);
shallow.EU[0].id = 99;
console.log(orders[0].id); // 1 (top-level copy protects this)
shallow.EU[0].items.push("pad");
console.log(orders[0].items); // ["pen", "pad"] (nested array is still shared)
const deep = Object.groupBy(structuredClone(orders), (o) => o.region);
deep.US[0].items.push("cap");
console.log(orders[1].items); // ["ink"]Copying costs time and memory proportional to the size of your data, so only do it when you plan to mutate. If you only read, filter, count, or sum groups, the shared references cost nothing.
Prefer Building New Values Over Mutating
A safer habit is to never mutate grouped elements at all. When you need changed data, produce new objects during post-processing. The source and the groups stay untouched, and you get a separate result.
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
const restocked = Object.fromEntries(
Object.entries(byType).map(([type, items]) => [
type,
items.map((item) => ({ ...item, quantity: item.quantity + 10 })),
])
);
console.log(restocked.fruit[0].quantity); // 10
console.log(inventory[1].quantity); // 0
console.log(byType.fruit[0].quantity); // 0Catching Accidental Mutation with Object.freeze
If shared data must never change, freeze the elements before grouping. In strict mode, which ES modules and class bodies use automatically, writing to a frozen object throws a TypeError. In sloppy-mode scripts, the write fails silently instead, so the "use strict" directive matters here.
"use strict";
const products = [
Object.freeze({ name: "pen", type: "office" }),
Object.freeze({ name: "mug", type: "kitchen" }),
];
const byType = Object.groupBy(products, (p) => p.type);
try {
byType.office[0].name = "marker";
} catch (error) {
console.log(error instanceof TypeError); // true
}
console.log(products[0].name); // "pen"Object.freeze is shallow. A frozen object whose property holds an array still allows that array to be changed. To lock down nested data, freeze it recursively or use an immutable data library.
Edge Cases Worth Knowing
- Duplicate references in the source. If the same object appears twice in the input, the callback runs twice and the object can land in two groups, or twice in one group. Mutating it through any of those slots changes it everywhere.
- Mutating inside the callback. The key callback receives the real element. Writing to it, for example
(item) => (item.seen = true, item.type), changes the source. Keep callbacks pure and use them only to compute keys. - Object keys in
Map.groupBy. When your callback returns an object as the key, theMapstores that key by reference too. Mutating the key object does not move entries, because lookups compare identity with SameValueZero, not contents.
Exercise
Given const list = [{ n: 1 }, { n: 2 }, { n: 3 }] and const g = Object.groupBy(list, (x) => (x.n > 1 ? "big" : "small")), what do list.length, list[1].n, and g.big.length print after running g.big.pop(); g.big[0].n = 20; list.push({ n: 5 });?
Show answer
list.length is 4, because pop only removes from the new group array, and the later push adds one element to list. list[1].n is 20, because after popping { n: 3 }, g.big[0] is the same object as list[1], so the assignment changes the source. g.big.length is 1, because the pop left one element and the object pushed onto list afterward is not added to any group.
Exercise
You group user records by role, then let an admin panel edit role directly on objects taken from the groups. Users keep showing up under their old role. Explain why and name two fixes.
Show answer
The edits change the shared user objects, so the role property updates, but group membership was fixed when Object.groupBy ran. The objects stay in their original arrays. One fix is to regroup from the source data after each edit. Another is to treat groups as read-only: apply edits to the source records (or create updated copies with spread syntax), then rebuild the grouped view from that data.