Change Arrays By Copy With toSorted And with
Sort, reverse, and replace by index with toSorted, toReversed, and with — each returns a new array so readers of the original never observe a mutation.
Code
// ES2023 copy-then-change 数组方法:toSorted / toReversed / with
const scores = [88, 42, 95, 67];
// toSorted 返回排序副本;sort 会原地修改共享数组
const ranked = scores.toSorted((a, b) => a - b);
console.log('ranked:', ranked.join(','));
console.log('source untouched:', scores.join(','));
// with(index, value) 替换单个元素并返回新数组,负索引从末尾数
const corrected = scores.with(1, 50).with(-1, 99);
console.log('corrected:', corrected.join(','));
// toReversed 反转副本
console.log('reversed:', scores.toReversed().join(','));
// 链式:先生成新数组再排序,全程不改 source
const podium = scores.with(0, 70).toSorted((a, b) => b - a);
console.log('podium:', podium.join(','), '| source:', scores.join(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
ranked: 42,67,88,95
source untouched: 88,42,95,67
corrected: 88,50,95,99
reversed: 67,95,42,88
podium: 95,70,67,42 | source: 88,42,95,67What the code does
Top-level bindings scores, ranked, corrected, podium hold the demo state — nothing sits inside a function scope.
Applying it
The demo output is labeled (ranked:, source untouched:, corrected:), so every printed line maps back to its originating operation.
Statements that matter
const podium = scores.with(0, 70).toSorted((a, b) => b - a);
const ranked = scores.toSorted((a, b) => a - b);
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `scores`, `ranked`, `corrected`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.