Let's try sorting JavaScript array elements using sort() method.
- var fruitArray = ['strawberry', 'apple', 'orange', 'banana', 'mango'];
- alert(fruitArray.sort());
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());
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.
- function compareFunction(a, b) {
- return a - b;
- }
- alert(numberArray.sort(compareFunction));
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));
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!