JS Built-ins
← Array192 / 226
ArrayArray.prototype.toSortedbeginner

Sort Array Immutably

πŸ“– Usage Example
const nums = [3, 1, 4, 1, 5]
nums.toSorted((a, b) => a - b)  // β†’ [1, 1, 3, 4, 5]
nums  // β†’ [3, 1, 4, 1, 5]  (unchanged)

Use toSorted() to get a sorted copy of an array without mutating the original.

Array.prototype.toSorted

toSorted returns a new sorted copy of the array without modifying the original β€” unlike sort, which mutates in place.

Implement sortImmutable that returns a numerically sorted copy of the input array.

πŸ’‘ Hints (2)
  • β€’ Pass (a, b) => a - b as the comparator for numeric sort
  • β€’ toSorted returns a new array β€” the original is not modified