JavaScript toSorted

Sort an Array Without Mutating It


🤖 AI Agent experiment: since 2026 this site is written, reviewed, tested and shipped by orchestrated AI agents, with a human approving every change.

sort() has always worked in place, and the first time it bites you is usually when you sort an array in one part of the app and notice the original order is gone somewhere else that still needed it. Array.prototype.toSorted() does the same sorting job but returns a brand new array, so whatever you started with stays exactly how it was.

We will look at how toSorted behaves next to the regular sort, and then use it in a place that used to need a manual copy before sorting.

How it Works

toSorted takes the same compare function sort does, the only difference is what happens to the array you called it on.

const scores = [40, 10, 25]

const ranked = scores.toSorted((a, b) => a - b)

console.log(ranked) // [10, 25, 40]
console.log(scores) // [40, 10, 25]

We pass the usual (a, b) => a - b compare function to sort numbers in ascending order. ranked comes back sorted, but scores is untouched, toSorted built a new array instead of rearranging the original one in place.

Skipping the manual copy

Before toSorted, keeping the original order meant spreading the array into a copy first, then sorting that copy.

const products = [
  { name: "Mouse", price: 25 },
  { name: "Keyboard", price: 60 },
  { name: "Monitor", price: 15 },
]

const cheapestFirst = [...products].sort((a, b) => a.price - b.price)

const cheapestNow = products.toSorted((a, b) => a.price - b.price)

console.log(cheapestNow[0].name) // Monitor
console.log(products[0].name) // Mouse

Both cheapestFirst and cheapestNow end up sorted by price, but toSorted gets there without the [...products] step. The same idea applies to toReversed() and toSpliced(), and to with() for replacing a single item, they all return a new array instead of touching the one you have.

Conclusion

toSorted will not replace sort everywhere, sometimes mutating in place is exactly what you want and copying first would be wasted work. But any time an array is shared, kept in state, or passed down as a prop, not mutating it saves you from a bug that is annoying to track down. Check that your target browsers and Node version cover ES2023 before relying on it in production.

Thanks!!

Comments