DEV Community

Jack Huynh
Jack Huynh

Posted on • Edited on

1

Javascript (ES14): toSorted()

ECMAScript proposal "Change Array by copy" by Robin Ricard and Ashley Claymore has been merge into ECMAScript standard. This proposal brings a lot of new toys, one of which is new array method: toSorted().

The toSorted() method is similar to sort

// Functionless
toSorted()

// Arrow function
toSorted((a, b) => { /* … */ })
Enter fullscreen mode Exit fullscreen mode

The only difference is that it does not change the original array, calling this method returns a changed copy of the original array.

sort()

const arr = [3, 4, 2, 5, 1];

console.log(arr.sort())
// [1, 2, 3, 4, 5] Returns a reference to original array, now sorted

console.log(arr)
// [1, 2, 3, 4, 5] The original array is mutated
Enter fullscreen mode Exit fullscreen mode

toSorted()

const arr = [3, 4, 2, 5, 1];

console.log(arr.toSorted()) 
// [1, 2, 3, 4, 5] Returns a new copy of arr that is sorted

console.log(arr) 
// [3, 4, 2, 5, 1] The original array is not affected
Enter fullscreen mode Exit fullscreen mode

For more information, check out the following resources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay