JavaScript Array.prototype.sort() vs Array.prototype.toSorted()

The sort() array method sorts its elements in place (no copy is made) and returns a reference to the same array. Hence the array is mutated. The default sort order of this function is ascending but we can pass a compare function to define our own behaviour (like sorting in descending order).

> const arr = [3, 4, 2, 5, 1]
undefined
> arr.sort() // Returns a reference to the original array, now sorted
[1, 2, 3, 4, 5]
> arr // Original array mutated
[1, 2, 3, 4, 5]

Here’s another example of sorting the array in descending order with a custom compare function:

> const arr = [3, 4, 2, 5, 1]
undefined
> arr.sort((a, b) => { return b - a; })
[5, 4, 3, 2, 1]
> arr
[5, 4, 3, 2, 1]

You can read more about the details of the sort() function and especially the comparator on MDN.

Now, on the other hand, the TC39 Change Array by copy proposal introduced a new method Array.prototype.toSorted() that does the same thing as sort() except it returns a new copy of the sorted array instead of mutating the original one.

> const arr = [3, 4, 2, 5, 1];
undefined
> arr.toSorted()
[1, 2, 3, 4, 5] // Returns a new copy of arr that is sorted
> arr
[3, 4, 2, 5, 1] // Original array is not mutated

> arr.toSorted((a, b) => b - a) // Custom comparator to sort in descending order
[5, 4, 3, 2, 1]
> arr
[3, 4, 2, 5, 1] // No mutation!

Leave a Reply

Your email address will not be published. Required fields are marked *