Array Sort in JavaScript

In JavaScript array sort() method is used to sort the element in an with some order. By default this method follow the ascending order of sorting the element in an array while you can change it's order to descending by modification of the array sort() method.

Syntax of Array Sort in JavaScript

The syntax of array sort() method is given as:
array.sort(compareFunction)


Example of Array Sort method

In this example array sort method is applied to show the courses.

<script type = "text/javascript">
var courses =["HTML","CSS","JQuery","Bootstrap"]  
var result =courses.sort();  
document.writeln(result);   
</script>                  
        

Output of above code


Second Example of Array Sort method

In this example numeric values are given without any order. Array sort method is applied to show the result in ascending order.
Let's see a simple example to sort the array of integer elements.

<script type = "text/javascript">
var num =[2,4,1,8,5];  
var result=num.sort();  
document.writeln(result);    
</script>                  
        

Output of above code


Example of Array in descending order

In this method some modification are applied in array sort() method to show the result in descending order.
Let's see an example to arrange the elements in descending order using function.

<script type = "text/javascript">
var num =[2,4,1,8,5];  
var result=num.sort(function compare(x,y)  
{  
  return x-y;  
});  
document.writeln(result);       
</script>                  
        

Output of above code


Example of Reversing an Array

The reverse() method reverses the elements in an array. You can use it to sort an array in descending order:

<script type = "text/javascript">
var names = ["Imran", "Irfan", "Amir", "Farhan"];
document.write(names.sort() + "<br/>");        
document.write(names.reverse());    
</script>                  
        

Output of above code








The Best

Comment here

If you have any query, if you want to know something about any of technical course related to computer science field, if you have any suggestion about relevant to uploaded content or if you anything wrong here (any mistake in content) than please contact us. Keep in mind, comment should be according to community guidelines.