Open In App

How toSorted() method is different from sort() in JavaScript

In JavaScript, sort() and toSorted() methods do the same job as sorting but toSorted() does not change the original array. sort() method changes the original array. Below we have explained both the methods.

Table of Content



Sort() Method:

Syntax:

arr.sort()

Example: In this example, We have used sort() method to sort an array. Here, we can see that sort() method change the original array.




let arr = [3,4,1,2,8,2];
let arr2 = arr.sort();
 
console.log("arr = ",arr);   
console.log("arr2 = ",arr2);   

Output:

arr =  [ 1, 2, 2, 3, 4, 8 ]
arr2 = [ 1, 2, 2, 3, 4, 8 ]

toSorted() Method:

The toSorted() method of array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order and original array won’t get affected.



Syntax:

let arr2 = arr.toSorted()

Example: In this example, We have used toSorted() method. Here we can see that toSorted() method does not change the original array.




let arr = [3,4,1,2,8,2];
let arr2 = arr.toSorted();
console.log("arr ="arr);
console.log("arr2 = "arr2);

Output:

arr = [3, 4, 1, 2, 8, 2]
arr2 = [1, 2, 2, 3, 4, 8]
Article Tags :