# .toSorted()

> The `.toSorted()` JS method returns a new array with the elements sorted in a specific order, without modifying the original array.

## How do I sort an array without mutating it in JavaScript?

The method that returns a new array with the elements sorted according to the provided comparison function, without changing the original array. Unlike `.sort()`, this method doesn't modify the original array.

- Topic: Array
- Type: method
- Browser support: Chrome 110+, Chrome Android 110+, Edge 110+, Firefox 115+, Firefox Android 115+, Safari 16+, Safari iOS 16+

## Example

Wrong:

```js
const byPrice = products
  .sort((a, b) => a.price - b.price);
```

Right:

```js
const byPrice = products
  .toSorted((a, b) => a.price - b.price);
```

`sort()` reorders `products` itself; `toSorted()` returns a sorted copy and leaves the source alone.

## Common mistakes

- Calling `toSorted()` on numbers with no comparator and getting string order.

## Key points

- Numbers are sorted with a comparator, like `toSorted((a, b) => a - b)`.
- Sorted copies for rendering use `toSorted()` instead of `sort()` on state.
- Code that must run in older browsers falls back to `[...arr].sort()`.

## Interview questions

### What is the difference between `sort()` and `toSorted()`?

`sort()` reorders the array in place. `toSorted()` returns a new sorted array and leaves the original untouched.

### Is `toSorted()` stable?

Yes. Like `sort()`, it keeps equal elements in their original order.

## Related cards

- [.sort()](https://wonderium.dev/js/array-sort.md)
- [.toReversed()](https://wonderium.dev/js/array-to-reversed.md)
- [.localeCompare()](https://wonderium.dev/js/string-locale-compare.md)
- [Intl.Collator](https://wonderium.dev/js/intl-collator.md)
- [useState()](https://wonderium.dev/react/use-state.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/array-to-sorted
- Last updated: 2026-11-25
