Sorting JavaScript Array Using Sort() Method

Let's try sorting JavaScript array elements using sort() method.

  1. var fruitArray = ['strawberry''apple''orange''banana''mango'];  
  2. alert(fruitArray.sort()); // returns apple,banana,mango,orange,strawberry  

By default, the sort() method sorts the values as strings in alphabetical and ascending order. So far, so good.
But now, let's try to sort some numeric elements.

  1. var numberArray = [4, 13, 2, 31, 5];  
  2. alert(numberArray.sort()); // returns 13,2,31,4,5  

It's returning unexpected results because of the following reasons.

Always keep in mind that sorting compares values by converting them to strings and then sorts that strings alphabetically which means that numbers are not sorted numerically.

But we can fix this by providing the optional parameter to sort method, which controls how sorting is done. Basically, it will be a function which has the following signature.

function compareFunction( a , b )

This function compares a and b and should return:

  • An integer less than zero (e.g., -1) if a is less than b;
  • Zero if a is equal to b;
  • An integer greater than zero (e.g., 1) if a is greater than b.

Now, let's sort that numeric array by passing the comparing function to sort method.

Firstly, we need to write a function which we can pass as a parameter to sort method. That function can guide the sort method in which order we need to sort our elements.

  1. function compareFunction(a, b) {  
  2.     return a - b;  
  3. }  
  4. alert(numberArray.sort(compareFunction)); //returns 2,4,5,13,31  

If we want to sort a numeric array in descending order, then we just need to change the logic written inside the compare Function, as given below.

  1. function compareFunction(a, b)   
  2. {  
  3.     return b - a;  
  4. }  
  5. alert(numberArray.sort(compareFunction)); // returns 31,13,5,4,2  
If you enjoyed this post, I’d be very grateful if you help it spread by emailing it to a friend, or sharing it on Twitter or Facebook. Thank you!