Arrays in Navigator 4.0 and up as well as in Internet Explorer 4.0 and up feature the sort() method, which sorts the elements of a given array. Its general syntax is:
arrayVar.sort(compareFunction);
compareFunction specifies a user-defined function that determines the sort order. If omitted, the elements are sorted in a lexicographic ("dictionary" or "telephone book," not numerical) order, according to the string conversion value of the array elements. For example, if two elements in an array are 9 and 80, 80 is sorted to a lower index than 9 because the string "80" comes before the string "9" in lexicographic order.
If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:
compareFunction(a, b) returns a value less than zero, b is sorted to a lower index than a.
If compareFunction(a, b) returns zero, a and b are left unchanged with respect to each other, but sorted with respect to all different elements.
If compareFunction(a, b) returns a value greater than zero, a is sorted to a lower index than b.
A compare function should have the following structure:
function compareFunction(a, b) {
if (a is less than b according to the sorting order)
return -1;
if (a is greater than b according to the sorting order)
return 1;
return 0;
}
Here is an example from our script in Column 15, where byName() serves as the compare function:
function byName(a, b) {
var anew = a.name.toLowerCase();
var bnew = b.name.toLowerCase();
if (anew < bnew) return -1;
if (anew > bnew) return 1;
return 0;
}
Notice that we are actually sorting objects, not strings. These objects are sorted according to their name property (a.name and b.name). While the default sorting method is case-sensitive, the byName() function ensures a case-insensitive sorting pattern. Therefore, the name property of the function's arguments is converted to an all-lowercase string via the toLowerCase() method.
Learn more about sorting arrays in Column 15, Lookup Lists.
People who read this tip also read these tips:
Look for similar tips by subject:
|