DEV Community

Jack Huynh
Jack Huynh

Posted on • Updated on

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

Top comments (0)