Sub topic 10
Chaining copying methods into pipelines
This chapter assumes you already know how toSorted, toSpliced, toReversed, and with work on their own. It also assumes you know that their copies are shallow. The focus here is on combining them. Each copying method returns a new array, so you can call another method on its result. The result is a pipeline: a chain of steps where each step receives the output of the previous one, and the original array stays the same.
Why copying methods chain cleanly
A method can only continue a chain if it returns an array. The mutating methods are inconsistent about this. Some return the same array after changing it, some return a number, and splice returns a different array that holds the deleted elements. The copying methods always return a new array of the expected shape. That makes their behavior in a chain easy to predict.
| Method | Return value | Safe to chain? |
|---|---|---|
| `sort`, `reverse` | The same array, mutated | Chains, but changes the original |
| `splice` | A new array of the **deleted** elements | Chains on the wrong data |
| `push`, `unshift` | The new length (a number) | No, the chain breaks |
| `toSorted`, `toReversed` | A new array | Yes |
| `toSpliced` | A new array with the edit applied | Yes |
| `with` | A new array with one index replaced | Yes |
| `map`, `filter`, `slice`, `concat` | A new array | Yes |
The copying methods also fit with the older non-mutating methods (map, filter, slice, concat). You can now write a whole data transformation without a mutating call.
A first pipeline: a leaderboard
const players = [
{ name: "Ada", points: 92 },
{ name: "Linus", points: 75 },
{ name: "Grace", points: 98 },
{ name: "Alan", points: 75 }
];
const topNames = players
.toSorted((a, b) => b.points - a.points)
.toSpliced(3)
.map((p) => p.name);
console.log(topNames); // ["Grace", "Ada", "Linus"]
console.log(players.map((p) => p.name)); // ["Ada", "Linus", "Grace", "Alan"]Here is what each step does:
toSortedproduces a new array ordered by points, highest first. The sort is stable, so Linus stays ahead of Alan because Linus came first in the input.toSpliced(3)has nodeleteCount, so it removes everything from index 3 to the end.slice(0, 3)does the same thing and is often clearer. Pick one and use it consistently.mapturns the objects into names.
players keeps its original order. The objects inside it are still the same objects, because every step makes a shallow copy.
The classic chaining bugs
Chaining off `splice`
splice returns the elements it removed, so a method chained after it runs on the wrong data:
const items = ["a", "b", "c", "d"];
const wrong = items.splice(1, 1).map((s) => s.toUpperCase());
console.log(wrong); // ["B"]
console.log(items); // ["a", "c", "d"] (mutated)
const source = ["a", "b", "c", "d"];
const right = source.toSpliced(1, 1).map((s) => s.toUpperCase());
console.log(right); // ["A", "C", "D"]
console.log(source); // ["a", "b", "c", "d"]The first version has two bugs at once. The original array is mutated, and the result holds the deleted items. toSpliced fixes both.
Ending a chain with `push`
push returns a number. If you put it at the end of a chain, the variable holds a length:
const queue = ["b", "c"];
const broken = queue.toSpliced(0, 0, "a");
const length = broken.push("d");
console.log(length); // 4
const appended = queue.toSpliced(0, 0, "a").toSpliced(queue.length + 1, 0, "d");
console.log(appended); // ["a", "b", "c", "d"]
const appendedAlt = [...queue.toSpliced(0, 0, "a"), "d"];
console.log(appendedAlt); // ["a", "b", "c", "d"]
console.log(queue); // ["b", "c"]ES2023 has no copying version of push. Use concat, spread, or toSpliced(arr.length, 0, item). In the appended line, the second index is queue.length + 1 because the first step already made the array one element longer. Spread avoids that bookkeeping, which is why most people use it for appending.
Mixing `sort` into a chain
const original = [3, 1, 2];
const safe = original.filter((n) => n > 1).sort((a, b) => a - b);
console.log(safe, original); // [2, 3] [3, 1, 2]
const unsafe = original.sort((a, b) => a - b).map((n) => n * 10);
console.log(unsafe, original); // [10, 20, 30] [1, 2, 3]sort after filter only mutates the array that filter just made, so nobody else sees the change. sort at the start of a chain mutates original. Whether this is a bug depends on where the call sits in the chain, and that is a fragile thing to depend on. Replacing sort with toSorted everywhere removes the question.
Indices refer to the current step
with and toSpliced take positions. Those positions refer to the array that the previous step produced, not to the original:
const steps = ["write", "review", "ship"];
const result = steps.toReversed().with(0, "SHIP");
console.log(result); // ["SHIP", "review", "write"]Index 0 means "ship" here only because toReversed ran first. If you work out an index from the original array and then use it after a reordering step, you will edit the wrong element.
When the index depends on the data, you have to break the chain to compute it. That opens a quiet trap with with:
function markDone(list, label) {
const sorted = list.toSorted();
const i = sorted.indexOf(label);
if (i === -1) return sorted;
return sorted.with(i, label + " (done)");
}
console.log(markDone(["write", "review", "ship"], "ship"));
// ["review", "ship (done)", "write"]
console.log(markDone(["write", "review", "ship"], "deploy"));
// ["review", "ship", "write"]Without the guard, indexOf returns -1 for a missing label. with(-1, ...) accepts that as a valid negative index and silently replaces the last element. You get no RangeError and no warning, just wrong data. Check -1 explicitly every time an index comes from indexOf or findIndex.
Cost: every step allocates
Each copying step creates a full new array. A chain of four steps over n elements allocates about four arrays of size n, and each one becomes garbage once the next step has run. For the arrays common in UI code (tens to a few thousand items), this cost rarely shows up in a profile. It starts to matter in hot loops or with very large arrays.
If profiling shows the chain is a problem, copy once and mutate the private copy:
function topNamesFast(players, n) {
const copy = players.slice();
copy.sort((a, b) => b.points - a.points);
copy.length = Math.min(n, copy.length);
for (let i = 0; i < copy.length; i++) {
copy[i] = copy[i].name;
}
return copy;
}
const roster = [
{ name: "Ada", points: 92 },
{ name: "Grace", points: 98 },
{ name: "Linus", points: 75 }
];
console.log(topNamesFast(roster, 2)); // ["Grace", "Ada"]
console.log(roster.length); // 3The function still looks immutable from outside: the caller's array is never touched. Inside, it allocates one array instead of three. This pattern is called local mutation. Use it only when you have measured a problem. The chained version is easier to read and review.
Keeping pipelines readable and debuggable
Long chains are hard to inspect. These habits help:
- Put one step on each line, with the dot at the start of the line, so a reviewer can read the chain from top to bottom.
- When a chain grows past four or five steps, or when one step's argument depends on an earlier result, split it into named constants such as
const ranked = ...; const top = ...;. The intermediate arrays already exist, so naming them costs nothing extra. - To inspect a step without breaking the chain, add a temporary
.map((x) => x)and set a breakpoint inside it, or assign the step to a variable while you debug. - Remember that the chain protects only the arrays. If any step changes an element object, for example
map((p) => { p.seen = true; return p; }), that change reaches the original data through the shared references. Return new objects instead, withmap((p) => ({ ...p, seen: true })).
Exercises
Exercise
Given const nums = [5, 3, 8, 1];, what does nums.toSorted((a, b) => a - b).toSpliced(1, 2).with(-1, 0) return, and what is nums afterward?
Show answer
toSorted gives [1, 3, 5, 8]. toSpliced(1, 2) removes 3 and 5, which gives [1, 8]. with(-1, 0) replaces the last element, which gives [1, 0]. nums is still [5, 3, 8, 1] because each step returned a new array.
Exercise
A teammate writes const names = users.splice(0, 2).map(u => u.name); to get the names of the first two users without changing users. Explain both problems and give a fixed version.
Show answer
splice mutates users by removing the first two entries. The map still happens to receive those two removed users, but the original array has lost them. A fixed version is users.toSpliced(2).map(u => u.name) or users.slice(0, 2).map(u => u.name). Both leave users unchanged.
Exercise
Why can list.with(list.indexOf(x), y) corrupt data when x is not in the list, and how do you prevent it?
Show answer
indexOf returns -1 when x is missing, and with treats -1 as the last index. The call then replaces the last element instead of throwing. Store the index first, check whether it equals -1, and skip the update (or handle the missing case) before calling with.