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

var fruitArray = ['strawberry', 'apple', 'orange', 'banana', 'mango'];  
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.

var numberArray = [4, 13, 2, 31, 5];  
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 try sorting 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. That function can guide the sort method in which order we need to sort our elements.

function compareFunction(a, b) {  
    return a - b;  
}  
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.

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

If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend or sharing it on Twitter, LinkedIn, or Facebook. Thank you!

LEAVE A REPLY

Please enter your comment!
Please enter your name here