Sub topic 13
Copying and Combining Arrays Without Mutation
This chapter assumes you know how indexing works and how push, splice, and sort change an array in place. It covers how to get a new array when you need one and leave the original as it was. That matters when an array is shared, for example in application state, a function argument, or a value that other code still reads.
Copying with slice and spread
slice(start, end) returns a new array holding the elements from start up to, but not including, end. Called with no arguments, it copies the whole array. Spread syntax ([...arr]) gives the same full copy and is the more common idiom today.
const original = [1, 2, 3, 4, 5];
const middle = original.slice(1, 4); // [2, 3, 4]
const lastTwo = original.slice(-2); // [4, 5]
const copyA = original.slice(); // [1, 2, 3, 4, 5]
const copyB = [...original]; // [1, 2, 3, 4, 5]
console.log(copyA === original); // false (a different array)
console.log(original); // [1, 2, 3, 4, 5]Combining with concat and spread
concat joins arrays into a new one. Spread does the same thing, and it also lets you put extra values anywhere in the result.
const a = [1, 2];
const b = [3, 4];
console.log(a.concat(b, [5])); // [1, 2, 3, 4, 5]
console.log([0, ...a, ...b]); // [0, 1, 2, 3, 4]
console.log(a); // [1, 2] (unchanged)The ES2023 copying methods
Several mutating methods now have copying versions. Each one returns a new array and leaves the original unchanged.
| Mutating | Copying version | Result |
|---|---|---|
| `sort(fn)` | `toSorted(fn)` | Sorted copy |
| `reverse()` | `toReversed()` | Reversed copy |
| `splice(i, n, ...items)` | `toSpliced(i, n, ...items)` | Copy with elements removed or inserted |
| `arr[i] = v` | `with(i, v)` | Copy with one element replaced |
const scores = [30, 10, 20];
console.log(scores.toSorted((x, y) => x - y)); // [10, 20, 30]
console.log(scores.toReversed()); // [20, 10, 30]
console.log(scores.toSpliced(1, 1, 99, 98)); // [30, 99, 98, 20]
console.log(scores.with(-1, 0)); // [30, 10, 0]
console.log(scores); // [30, 10, 20]toSpliced returns the new array. It does not return the removed elements the way splice does. with accepts negative indexes, and it throws a RangeError if the index is out of range. These methods need Node.js 20+ or a current browser.
Copies are shallow
Every technique in this chapter makes a shallow copy. A shallow copy is a new outer array whose elements are the same values as before. When the elements are objects, both arrays point to the same objects.
const users = [{ name: 'Ana' }];
const copy = [...users];
copy[0].name = 'Zoe';
console.log(users[0].name); // 'Zoe' (same object)Exercise
Given const tasks = ['write', 'test', 'ship'];, write one expression that returns a new array with 'review' inserted between 'test' and 'ship' and leaves tasks unchanged. Then write a second expression that returns a copy with 'ship' replaced by 'deploy'.
Show answer
tasks.toSpliced(2, 0, 'review') returns ['write', 'test', 'review', 'ship']. tasks.with(-1, 'deploy') (or tasks.with(2, 'deploy')) returns ['write', 'test', 'deploy']. [...tasks.slice(0, 2), 'review', ...tasks.slice(2)] also works for the first expression. tasks stays ['write', 'test', 'ship'].
Exercise
After const a = [[1], [2]]; const b = a.slice(); b[0].push(9);, what is a, and why?
Show answer
a is [[1, 9], [2]]. slice makes a shallow copy, so b[0] and a[0] are the same inner array.