Syntax
values.toSorted(compare);
values.toSpliced(index, deleteCount, item);
values.with(index, replacement);Examples
Immutable Array Updates with Copying Methods: working example
Run this standalone example in a modern browser console unless another environment is specified. Expected result: Logs are 30,5,12; 5,12,30; 12,8,30; and 30,12 on separate lines.
const scores = [30, 5, 12];
const ranked = scores.toSorted((a, b) => a - b);
const corrected = scores.with(1, 8);
console.log(scores.join(","));
console.log(ranked.join(","));
console.log(corrected.toReversed().join(","));
console.log(scores.toSpliced(1, 1).join(","));- Expected result: Logs are 30,5,12; 5,12,30; 12,8,30; and 30,12 on separate lines.
- Numeric sorting needs an explicit numeric comparator.
- with replaces one position in a fresh array, and toSpliced removes from a fresh array.
Best practices
- Use copying methods when callers depend on the original array remaining intact.
- Do not mistake shallow copying for cloning nested records.
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification