Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

JavaScript | Sort() method

  • Difficulty Level : Medium
  • Last Updated : 14 Feb, 2019

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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 :