SORTING OF ARRAY USING JAVASCRIPT

Share the post

In this session, We will discuss the sorting of an array using JavaScript. As we are the programmer always have the requirement to sort the data alphabetically. In that case, we have to use the JavaScript method sort(). Using this method we can able to sort the values alphabetically. Now, we will see How to sort the array of strings?  

How to use sort() in JavaScript?

We will understand the sort() method used by using the below example.

Example :

var array = ["D","C","B","A"]; 
console.log("array before sorting " + array ); 
array.sort(); 
console.log("array after sorting " + array );

Output :

array before sorting D,C,B,A array after sorting A,B,C,D  

Please find the below image for more details :

Output
Output

In the above example, we can able to see the array has been sorted alphabetically. But, what to do in case of the array contains numeric value? If you have this question in your mind then use the below method to sort a numeric array small to a big number.

How to sort() numeric array?

If the array contains a number & if you want to sort it from a small to a larger number then kindly see the below example.

Example :

var array = ["100","50","150","200"]; 
console.log("array before sorting " + array ); 
array.sort(function(a, b){return a - b}); 
console.log("array after sorting " + array );  

Output :

array before sorting 100,50,150,200 array after sorting 50,100,150,200  

Please find the below image for more details :

Output
Output

In above example, we have sorted the numeric array.

Leave a Comment