
Sorting an array in Javascript is a snap.
You create an array and then call sort() method on that array. The Javascript sort() method sorts an array in lexicographical order. This method is very useful in sorting alphanumeric values of an array.
Here is an example
var ages = new Array (23,6,2,16,48,9,6);
ages.sort();
The array will become (16,2,23,48,6,6,9)
Fortunately, the work around for this problem is quite simple.
You use the same sort() method but with an additional argument. This optional argument is a reference to a comparison method that tells sort() how to compare the elements.
Here is very simple compare method. What you name your function is not important. You can call it whatever you like. The important things are the two arguments and the return statement.
function compare(a,b){
return a-b;
}
Example:
var ages = new Array (23,6,2,16,48,9,6);
ages.sort(compare);
Result: (2,6,6,9,16,23,48).
So how does it all work? There is no magic trick here. When you provide your comparison method to sort() you control how the elements are compared. If your compare(a,b) method returns
- a positive value (a number greater than 0) ‘a’ will be put before ‘b’.
- a negative value (a number greater than 0) ‘b’ will be put before ‘a’.
- 0 (meaning ‘a’ and ‘b’ are equal) then the positions of these two elements will not change in the sorted array.
This array is sorted in ascending order. If you want to sort in descending order use following method
function compare(a,b){
return b-a;
}
Hope this helps.
Popularity: 10% [?]
If you enjoyed this post, make sure you subscribe to my RSS feed!Related posts:
- Sort numbers in Java to find minimum and maximum values without using Array
- Automatically Sort Vector Elements
- Validate U.S Phone Numbers using JavaScript Regular expression.
- Three ways to find minimum and maximum values in a Java array.
- How to convert an ArrayList to array in Java






whoa thanks! bighelp!