JavaScript | Sort() method
The array.sort() is an inbuilt method in JavaScript which is used to sort the array. An array can be of any type i.e. string, numbers, characters etc.
Syntax:
array.sort()
Here array is the set of values which is going to be sorted.
Parameters: It does not accept any parameters.
Return values: It does not return anything.
Examples:
Input: var arr = ["Manish", "Rishabh", "Nitika", "Harshita"]; Output: Harshita, Manish, Nitika, Rishabh Input: var arr = [1, 4, 3, 2]; Output: 1, 2, 3, 4
Code #1: To sort an array of strings:
<html> <body> <p>Click on the Sort button to sort the array</p> <!-- button for click event --> <!-- onclick event is generated when the button is clicked --> <p id="demo"></p> <script> <!-- array of names --> var names = [" Manish", " Rishabh", " Nitika", " Harshita"]; document.getElementById("demo").innerHTML = names; <!-- sortAlphabet function that sort above array alphabetically --> function sortAlphabet() { names.sort(); document.getElementById("demo").innerHTML = names; } </script> <button onclick="sortAlphabet()"> Sort </button> </body> </html> |
Output:
Before clicking the “sort” button-

After clicking the “sort” button-

Code #2: To sort an array of integers:
<html> <body> <p>Click on the Sort button to sort the array</p> <!-- button for click event --> <!-- onclick event is generated when the button is clicked--> <p id="demo"></p> <script> <!-- array numbers --> var numbers = [7, 1, 6, 9, 2]; document.getElementById("demo").innerHTML = numbers; <!-- sortNumber function that sort the array --> function sortNumber() { numbers.sort(); document.getElementById("demo").innerHTML = numbers; } </script> <button onclick="sortNumber()"> Sort </button> </body> </html> |
Output:
Before clicking the “sort” button-

After clicking the “sort” button-

Recommended Posts:
- How to sort strings in JavaScript?
- JavaScript | Array sort()
- How to sort rows in a table using JavaScript?
- JavaScript | typedArray.sort() with Examples
- Sort an Object Array by Date in JavaScript
- Merge Sort for Linked Lists in JavaScript
- Sort array of objects by string property value in JavaScript
- JavaScript | Array from() Method
- JavaScript | Array map() Method
- JavaScript | exec() Method
- JavaScript | compile() Method
- JavaScript | Replace() Method
- JavaScript | Array.from() method
- JavaScript | getTime() Method
- Javascript | Window prompt() Method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



