Main Page

comparison function

return –1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
As you can see, a comparison function compares two values, which is why a comparison function
always has two arguments. If the first argument should come before the second argument, the function
returns –1. If the first argument should come
the second argument, the function returns 1. If, how-
ever, the arguments are equal, the function returns 0. The comparison function is used in the
method like this:
The basic comparison function pattern described previously sorts an array in ascending order. To sort in
descending order, you just reverse 1 and –1:
function comparison_function_desc(value1, value2) {
if (value1 < value 2) {
return 1;
} else if (value1 > value2) {
return -1;
} else {
return 0;
If this pattern sounds familiar, that’s because the
method works the same
way. So if you are sorting an array of strings, you can use this method directly:
function compareStrings(string1, string2) {
return string1.localeCompare(string2);
This function causes an array of strings to be sorted in ascending order. To sort an array in descending
order, just put a negative sign in front of the call:
function compareStringsDesc(string1, string2) {
return -string1.localeCompare(string2);
By adding the negation operator, 1 becomes –1, –1 becomes 1, and 0 remains unchanged.
Now, go back to the previous example, in which numbers are sorted incorrectly. You can easily remedy
the problem by writing a comparison function that transforms the arguments into numbers first and
then compares them:
function compareIntegers(vNum1, vNum2) {
var iNum1 = parseInt(vNum1);
var iNum2 = parseInt(vNum2);
Chapter 12
15_579088 ch12.qxd 3/28/05 11:40 AM Page 368

JavaScript EditorFree JavaScript Editor     Ajax Editor