Sub topic 2
Inserting, Removing, and Replacing with toSpliced
This chapter assumes you know how splice works, how array indexing works, and how primitive values differ from object references.
Inserting, removing, and replacing with toSpliced
toSpliced(start, deleteCount, ...items) takes the same arguments as splice. The difference is what it returns. splice changes the array in place and returns the deleted elements. toSpliced returns the new array and leaves the original unchanged.
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"]Replacing one element with with
with(index, value) is the copying version of arr[index] = value. It returns a copy with one position replaced.
Negative indices and out-of-range errors
with counts negative indices from the end, the same way at does. Bracket assignment would add a new element past the end of the array. with throws a RangeError for an out-of-range index instead.
const values = [1, 2, 3, 4, 5];
console.log(values.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(values.with(-1, 0)); // [1, 2, 3, 4, 0]
console.log(values); // [1, 2, 3, 4, 5]
try {
values.with(10, 0);
} catch (err) {
console.log(err instanceof RangeError); // true
}toReversed: the related copying method
toReversed() is the copying version of reverse(). For example, [1, 2, 3].toReversed() returns [3, 2, 1] and leaves the original array as it was.
Shallow copies: what stays shared
All of these methods make shallow copies. The new array is a new container, but it holds the same object references as the original.
const users = [{ name: "Linus" }, { name: "Ada" }];
const byName = users.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(byName[0] === users[1]); // true
byName[0].name = "Grace";
console.log(users[1].name); // "Grace"If you need to change an element object without affecting the original, copy that object as well, for example with { ...obj }.
Exercise
Given const a = [{ n: 1 }, { n: 2 }], what does a.with(-1, { n: 9 })[1].n log, and what is a[1].n afterwards? What happens with a.with(5, {})?
Show answer
The first expression gives 9. a[1].n is still 2, because with put a new object at index 1 of the copy and left the original's object alone. a.with(5, {}) throws a RangeError, because index 5 is out of range for a two-element array.