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

JavaScript code to show the working of this function:

Code #1: To sort an array of strings:



filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:
Before clicking the “sort” button-

After clicking the “sort” button-

Code #2: To sort an array of integers:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:
Before clicking the “sort” button-

After clicking the “sort” button-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.