Copying instead of mutating in JavaScript
The 2023 methods return a new array where the old ones edited in place.
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
const reversed = original.toReversed();
const replaced = original.with(0, 99);
const spliced = original.toSpliced(1, 1);
console.log(original, sorted, reversed, replaced, spliced);
const mutated = [3, 1, 2];
mutated.sort();
console.log(mutated); // the original order is gone
console.log([[1, [2]], [3]].flat(2), Array.from({ length: 3 }, (_, i) => i));
How it works
toSorted,toReversedandwithleave the original alone.sortandreversestill mutate, which surprises people.at,flatand spread cover the rest.
Keywords and builtins used here
Arrayconstfromwith
The run, in numbers
- Lines
- 14
- Characters to type
- 436
- Tokens
- 145
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 97 seconds.
Step 3 of 10 in Arrays, step 19 of 43 in Language basics.