Skip to content
Related Articles

Related Articles

JavaScript | Sort() method

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 14 Feb, 2019
View Discussion
Improve Article
Save Article

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:




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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!