Sub topic 5
Inserting, removing, and replacing with toSpliced
splice is the most flexible array method in JavaScript. It can insert, remove, and replace elements in one call. It also mutates the array it is called on, and it returns the deleted elements instead of the updated array. toSpliced keeps the flexibility and fixes both problems. It takes the same arguments as splice, leaves the original array untouched, and returns the new array.
This chapter assumes you already know how splice works, including its start, deleteCount, and items arguments. It also assumes you are comfortable with arrow functions and with the difference between mutating and copying methods, which earlier chapters covered.
The signature
array.toSpliced(start, skipCount, ...items)startis the index where the change begins. Negative values count from the end.skipCountis how many elements to leave out of the new array, starting atstart. Insplicethis argument is calleddeleteCount. The behavior is the same, but nothing is deleted from the original, so the specification uses the name "skip".itemsare zero or more values to insert atstart.
The result is a new array. Its length is the original length minus the elements actually skipped plus the number of items inserted.
The three operations
The arguments you pass decide which operation you get. A skipCount of zero with items inserts. A skipCount with no items removes. A skipCount with items replaces.
const months = ["Jan", "Mar", "Apr", "May"];
const inserted = months.toSpliced(1, 0, "Feb");
console.log(inserted); // ["Jan", "Feb", "Mar", "Apr", "May"]
const removed = months.toSpliced(2, 2);
console.log(removed); // ["Jan", "Mar"]
const replaced = months.toSpliced(1, 1, "Feb");
console.log(replaced); // ["Jan", "Feb", "Apr", "May"]
console.log(months); // ["Jan", "Mar", "Apr", "May"]The last line shows that months is unchanged after all three calls. Each call starts from the same original, so you can derive several variants from one array without copying it first.
Replacement does not have to be one-for-one. You can skip two elements and insert five, or skip three and insert one. The new array grows or shrinks to fit.
const steps = ["plan", "draft", "ship"];
const expanded = steps.toSpliced(1, 1, "outline", "draft", "edit");
console.log(expanded); // ["plan", "outline", "draft", "edit", "ship"]splice versus toSpliced
The two methods look alike, so code that switches from one to the other often trips on the return value.
| Aspect | splice | toSpliced |
|---|---|---|
| Changes the original array | Yes | No |
| Returns | An array of the deleted elements | The new, updated array |
| Arguments | start, deleteCount, ...items | start, skipCount, ...items |
| Holes in sparse arrays | Preserved | Become undefined |
| Available on typed arrays | No | No |
If you need the removed elements as well as the new array, take them with slice first. slice(start, start + count) returns exactly the elements that toSpliced(start, count) leaves out.
const a = [1, 2, 3, 4];
const deleted = a.splice(1, 2);
console.log(deleted); // [2, 3]
console.log(a); // [1, 4]
const b = [1, 2, 3, 4];
const next = b.toSpliced(1, 2);
const skipped = b.slice(1, 3);
console.log(next); // [1, 4]
console.log(skipped); // [2, 3]
console.log(b); // [1, 2, 3, 4]How the arguments are normalized
toSpliced converts and clamps its arguments the same way splice does. It never throws for an out-of-range index. This differs from with, which a later chapter shows throwing a RangeError.
const letters = ["a", "b", "c", "d", "e"];
// Negative start counts from the end
console.log(letters.toSpliced(-2, 1)); // ["a", "b", "c", "e"]
console.log(letters.toSpliced(-2, 0, "x")); // ["a", "b", "c", "x", "d", "e"]
// start past the end is clamped to the length, so items are appended
console.log(letters.toSpliced(10, 0, "z")); // ["a", "b", "c", "d", "e", "z"]
// Omitting skipCount skips everything from start to the end
console.log(letters.toSpliced(1)); // ["a"]
// Negative skipCount is clamped to 0
console.log(letters.toSpliced(1, -3)); // ["a", "b", "c", "d", "e"]
// No arguments at all returns a plain copy
const copy = letters.toSpliced();
console.log(copy); // ["a", "b", "c", "d", "e"]
console.log(copy !== letters); // trueThe rules, in order:
startis converted to an integer. A negative value has the length added to it, and the result is clamped to the range 0 to length.- If
startis not passed, nothing is skipped. IfskipCountis not passed, everything fromstartto the end is skipped. - Otherwise
skipCountis converted to an integer and clamped to the range 0 to (length minus start).
The only error toSpliced can throw for its arguments is a TypeError if the new length would exceed 2^53 − 1. You will not hit that with real arrays.
The findIndex trap
Because negative starts are legal, a missing index does not fail loudly. findIndex returns -1 when nothing matches, and toSpliced(-1, 1) removes the last element.
const tasks = [
{ id: 1, title: "Write" },
{ id: 2, title: "Review" },
{ id: 3, title: "Publish" }
];
// Buggy: removes "Publish" when the id is not found
const buggy = tasks.toSpliced(tasks.findIndex((t) => t.id === 99), 1);
console.log(buggy.map((t) => t.title)); // ["Write", "Review"]
// Safe: check for -1 first
function removeById(list, id) {
const index = list.findIndex((item) => item.id === id);
return index === -1 ? list : list.toSpliced(index, 1);
}
console.log(removeById(tasks, 99) === tasks); // true
console.log(removeById(tasks, 2).map((t) => t.title)); // ["Write", "Publish"]Returning the original array when nothing changes is deliberate. Code that compares references to detect changes, such as React's rendering checks, then sees correctly that there was no update.
Common patterns
Moving an element
Moving an item from one index to another is two toSpliced calls. The first removes the item, and the second inserts it at the target position in the shorter array.
function move(arr, from, to) {
return arr.toSpliced(from, 1).toSpliced(to, 0, arr[from]);
}
const queue = ["a", "b", "c", "d"];
console.log(move(queue, 0, 2)); // ["b", "c", "a", "d"]
console.log(move(queue, 3, 0)); // ["d", "a", "b", "c"]
console.log(queue); // ["a", "b", "c", "d"]The to index refers to positions after the removal. That is the usual meaning for drag-and-drop reordering.
Inserting into a sorted list
Find the first element larger than the new value, then insert before it. If none is larger, findIndex returns -1. Inserting at -1 would put the value before the last element, so map that case to the length.
function insertSorted(arr, value) {
const found = arr.findIndex((x) => x > value);
const index = found === -1 ? arr.length : found;
return arr.toSpliced(index, 0, value);
}
console.log(insertSorted([1, 3, 5], 4)); // [1, 3, 4, 5]
console.log(insertSorted([1, 3, 5], 9)); // [1, 3, 5, 9]Replacing the old spread-and-slice idiom
Before ES2023, a non-mutating insert usually looked like this:
const arr = [1, 2, 4];
const i = 2;
const before = [...arr.slice(0, i), 3, ...arr.slice(i)];
const after = arr.toSpliced(i, 0, 3);
console.log(before); // [1, 2, 3, 4]
console.log(after); // [1, 2, 3, 4]Both produce the same array. The toSpliced version states the intent in one call and avoids building two intermediate arrays.
What toSpliced does not change
toSpliced copies the array, not the elements inside it. Objects in the new array are the same objects as in the original, so changing a property through one array shows up in the other. The chapter on shallow copies covers this in detail. Sparse arrays and typed arrays also get their own chapters. In short, holes become undefined in the result, and typed arrays have no toSpliced method because their length is fixed.
Exercise
Given const xs = [10, 20, 30, 40], what do xs.toSpliced(-1, 0, 35) and xs.toSpliced(1) return, and what is xs afterward?
Show answer
xs.toSpliced(-1, 0, 35) returns [10, 20, 30, 35, 40], because -1 resolves to index 3 and the value is inserted before 40. xs.toSpliced(1) returns [10], because an omitted skipCount skips everything from index 1 to the end. xs is still [10, 20, 30, 40].
Exercise
A teammate converts const [removed] = items.splice(i, 1); to const [removed] = items.toSpliced(i, 1);. What does removed hold now, and how would you rewrite the code to get both the removed element and a new array without mutating items?
Show answer
removed now holds the first element of the new array, which is items[0] when i is not 0, or items[1] when i is 0. It does not hold the removed element. Rewrite it as const removed = items[i]; const next = items.toSpliced(i, 1);, or use items.slice(i, i + 1) if you want the removed part as an array.
Exercise
Write a function replaceRange(arr, start, end, ...items) that returns a new array where the elements from index start up to, but not including, end are replaced by items. It must not mutate arr.
Show answer
const replaceRange = (arr, start, end, ...items) => arr.toSpliced(start, end - start, ...items); For example, replaceRange([1, 2, 3, 4, 5], 1, 3, "x") returns [1, "x", 4, 5]. If end is less than start, skipCount is negative and is clamped to 0, so the items are inserted without removing anything.