JavaScriptArrays

Array.prototype.toSorted()

Returns a sorted copy of the array, leaving the original unchanged.

Returns
A new, sorted array.
Changes the original
No
On this page

Example

#
JavaScript
const prices = [79, 49, 59]
const sorted = prices.toSorted((a, b) => a - b)

console.log(sorted)
console.log(prices)
Console
[49, 59, 79]
[79, 49, 59]

Definition and usage

#

The toSorted() method works like sort(), but instead of sorting the array in place, it returns a new, sorted array. The original stays the same.

That’s convenient in code that avoids mutation, for example in React component state, where changing the original array can cause bugs that are hard to track down.

It belongs to the family of "copying" methods, together with toReversed(), toSpliced(), and with(). You pass a comparator the same way as in sort().

Syntax

#
Syntax
array.toSorted()
array.toSorted(compareFn)

Parameters

#
  • compareFn

    function (a, b)

    The comparator function, as in sort().

More examples

#
The family of copying methods
JavaScript
const steps = ['a', 'b', 'c']

console.log(steps.toReversed())
console.log(steps.with(1, 'B'))
console.log(steps.toSpliced(0, 1))
console.log(steps)
Console
['c', 'b', 'a']
['a', 'B', 'c']
['b', 'c']
['a', 'b', 'c']

Browser support

#

Widely available · since 2023

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • In application state, prefer toSorted() over sort(). You’ll avoid accidentally mutating the data.
  • In older code, [...array].sort(...) gives the same result.

Related entries

#

Spotted a mistake or missing an example? Write to us.