JavaScript
Sort an array without changing the original
Use toSorted to return a sorted copy of an array. It expresses the nonmutating operation directly and is useful when several parts of a program share the same array.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const scores = [8, 3, 5];
const ordered = scores.toSorted((a, b) => a - b);
console.log(JSON.stringify(ordered));
console.log(JSON.stringify(scores));How it works
The returned array has its own element positions, while scores retains its input order. This makes it easier to compute a sorted view without changing the data used by another component. A numeric comparator is still required for numeric ordering.
Limits and mistakes
The copy is shallow: objects inside both arrays still refer to the same objects. Older JavaScript engines may lack toSorted; copying with spread and then calling sort is an alternative when that compatibility matters.
Check the result
Expect [3,5,8] and then [8,3,5]. If sorting objects, verify separately that editing an object through the returned array also affects the shared record.
Sources
Reference documentation for the behavior used in this guide: