JS Built-ins
← Array196 / 226
ArrayArray.prototype.toSortedintermediate

toSorted Returns a New Reference

πŸ“– Usage Example
const arr = [3, 1, 2]
arr.sort((a,b)=>a-b)  // mutates arr β†’ [1, 2, 3]
const s = [3,1,2].toSorted((a,b)=>a-b)  // safe copy

Choose toSorted() over sort() when working in functional or immutable patterns.

Array.prototype.toSorted β€” New Array

Unlike sort, which sorts in place and returns the same reference, toSorted always returns a new array β€” the result is never === the input.

Implement toSortedReturnsNew which returns true if arr.toSorted() is a different reference than arr.

πŸ’‘ Hints (2)
  • β€’ Use strict inequality (!==) to compare array references
  • β€’ toSorted always allocates a new array, even if elements are identical