Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

Array.prototype.toSorted()

Reference for JavaScript Array.prototype.toSorted(): sort a copy of an array without mutating the original, comparator rules, default order and how it differs from sort().

The toSorted() method returns a new array with the elements sorted, and leaves the original array unchanged. It takes the same optional comparator as sort() and sorts the same way, including stable ordering.

Use it whenever you need a sorted view of data you must not modify, which removes the common [...array].sort() copy step.

JavaScript
const scores = [30, 5, 12];
const ordered = scores.toSorted((a, b) => a - b); // [5, 12, 30]
// scores is still [30, 5, 12]

Try it

JS Sorting without changing the source

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Sorting objects by two keys

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
array.toSorted()
array.toSorted(compareFn)
Name Description
compareFn Optional. Called as compareFn(a, b). Return a negative number to put a first, a positive number to put b first, or 0 to keep their order.

Return value: a new, sorted array.

Exceptions: a TypeError if compareFn is given and is neither a function nor undefined.

Usage notes

  • The original is not changed. Compare with sort(), which reorders the array itself and returns that same array.
  • Same default order as sort(). Without a comparator, elements are compared as strings by UTF-16 code units, so [10, 9, 1] becomes [1, 10, 9]. Pass (a, b) => a - b for numbers.
  • undefined values go to the end; holes are turned into undefined in the result (because the copy is always dense) and sort with them.
  • Shallow copy. Objects are shared between the original and the sorted copy; only the array is new.
  • Stable. Items that compare equal keep their original relative order.
  • For text, use localeCompare() or Intl.Collator to respect language rules.
  • Cost. It copies the array and sorts it: O(n log n) time and O(n) extra memory. If you do not need the original, sort() avoids the copy.
  • Fallback for older browsers: [...array].sort(compareFn) or array.slice().sort(compareFn).
  • Related copying methods: toReversed(), toSpliced() and with().

Browser support

Array.prototype.toSorted() is a recent addition (ES2023) available in current browsers, but not in older ones, so check a compatibility table if you support them.