JavaScript - Sort Arrays Without Mutations with toSorted()

Often, you'll need to sort your data in arrays.

One frustrating thing about the sort() method is that it mutates the array you call it on.

Thankfully, the new toSorted() method provides a very simple fix.

It works the same way as sort, except it returns a new value.

If you aren't sure what I mean, let me show you why sort() is bad:

Why the old sort method is bad 🚫

As a quick example of some potentially poor behavior, let me show you how Array.sort() mutates values:

const numbers = [10, 5, 40, 25];
const sorted = numbers.sort((a, b) => a - b);

When we run this code, sorted equals [5, 10, 25, 40], which I assume you expected.

But the problem now is that numbers also equals [5, 10, 25, 40], so we no longer have a reference to the original value if we need it.

How to use toSorted()

You can now call toSorted() on your arrays, which will return a new sorted array as a value:

const numbers = [10, 5, 40, 25];
const sorted = numbers.toSorted((a, b) => a - b);
// `sorted` equals [5, 10, 25, 40]
// `numbers` remains [10, 5, 40, 25] 🎉

Now, by changing the function to toSorted() we get a much more predictable behaviour since our values are not being mutated. 🎉

Just 2 characters are required to upgrade your logic so I think it's a no brainer replacement for sort().

Happy coding! ✌️

JavaScriptJS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.