Open in App
Not now

JavaScript Array sort() Method

• Difficulty Level : Basic
• Last Updated : 13 Dec, 2022

JavaScript Array.sort() Method is used to sort the array in place in a given order according to the compare() function. If the method is omitted then the array is sorted in ascending order.

Syntax:

`arr.sort(compareFunction)`

Parameters: This method accepts a single parameter as mentioned above and described below:

• compareFunction: This parameter is used to sort the elements according to different attributes and in a different order.
• compareFunction(a,b) < 0
• compareFunction(a,b) > 0
• compareFunction(a,b) = 0

Return value: This method returns the reference of the sorted original array.

Example 1:

JavaScript

 ``

Output:

```Geeks,for,Geeks
Geeks,Geeks,for```

Example 2: In this example, the sort() method arranges the elements of the array in ascending order.

JavaScript

 ``

Output:

```1,2,4,5,8
1,2,4,5,8```

Example 3: In this example, the sort() method the elements of the array are sorted according to the function applied to each element.

JavaScript

 ``

Output:

```2,5,8,1,4
2,5,8,1,4```

Example 3: In this example, we use the sort() method on the array of numbers & observe some unexpected behavior.

Javascript

 ``

Output:

`-120,0,100,20,30,5.2`

Our output should be -120, 0, 5.2, 20, 30, 100 but it’s not so, why? Because as we apply the direct sort() method, it would process accordingly: 100 would be placed before 20, as ‘2’ is larger than ‘1’, and similarly in the case of 30 & 5.2,  as ‘5’ is larger than ‘3’ thus, 30 would be placed before 5.2. We can resolve this unexpected error by using the sort() method for numerics using the following compare function:

Javascript

 ``

Output:

`-120,0,5.2,20,30,100`

Please go through this How to Sort Numeric Array using JavaScript?, to know how the javascript array sort function works

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers: The browsers supported by the JavaScript Array sort() method are listed below:

• Google Chrome 1 and above
• Edge 12 and above
• Firefox 1 and above
• Internet Explorer 5.5 and above
• Opera 4 and above
• Safari 1 and above

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.

Time Complexity: The time complexity of the sort() method varies & depends on implementation.

For example, in the Firefox web browser, it uses the merge sort implementation which gives time complexity as O(nlog n). Whereas, in Google Chrome web browser, it uses the Timsort implementation (a hybrid of merge sort and insertion sort), gives time complexity is O(nlogn).

My Personal Notes arrow_drop_up
Related Articles