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 buttoSorted()
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 ]
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 ]
π
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 ]
Top comments (0)