Open In App

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

Last Updated : 05 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • The sort() method is a built-in method for arrays in JavaScript that directly modifies the array in place.
  • By default, it sorts the elements as strings, so for numeric sorting, a comparison function needs to be provided.

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.

Javascript




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.

Javascript




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]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads