DEV Community

Cover image for sort() vs toSorted()
sundarbadagala
sundarbadagala

Posted on • Updated on

sort() vs toSorted()

DEFINITION 🔊

sort() 🔔
The sort() method of Array instances sorts the elements of an array in place and returns the reference to the same array,

toSorted() 🔔
The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements.

📌 sort() method will mutate the original array but toSorted() method won't affect original, It returns as new array

EXAMPLE 🔊

sort()

const arr1 = [4,1,7,2,9]
const arr2 = arr1.sort()

console.log(arr2)   //[ 1, 2, 4, 7, 9 ]
console.log(arr1)    //[ 1, 2, 4, 7, 9 ]
Enter fullscreen mode Exit fullscreen mode

toSorted()

const arr1 = [4,1,7,2,9]
const arr2 = arr1.toSorted()

console.log(arr2)   //[ 1, 2, 4, 7, 9 ]
console.log(arr1)    //[ 4, 1, 7, 2, 9 ]
Enter fullscreen mode Exit fullscreen mode

📌 toSorted() method currently works in node.js version >19 and Chrome and Edge (from version 110), Safari (from version 16), Firefox (from version 115). It's not supported in older versions.

Sort without mutating the original array and without using toSorted() method

const arr1 = [4,1,7,2,9]
const arr2 = [...arr].sort()

console.log(arr2)   //[ 1, 2, 4, 7, 9 ]
console.log(arr1)    //[ 4, 1, 7, 2, 9 ]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)