Main Page

The reverse() method

if (iNum1 < iNum2) {
return –1;
} else if (iNum1 > iNum2) {
return 1;
} else {
return 0;
}
}
If you apply this comparison function to the earlier example, the correct result is returned:
var arr = [3, 32, 2, 5]
arr.sort(compareIntegers);
alert(arr.toString()); //outputs “2,3,5,32”
This example now outputs the numbers in correct order (2, 3, 5, 32).
The reverse() method
You were introduced to the
reverse()
method, which simply reverses the order of the items in an
array, in Chapter 3, “Object Basics.” In this chapter, you learn that the
reverse()
method is an essential
part of sorting.
So, if you use a comparison function that sorts in ascending order, you can easily change the sort to
descending order by using the
reverse()
method after the
sort()
method:
var arr = [3, 32, 2, 5]
arr.sort(compareIntegers);
alert(arr.toString()); //outputs “2,3,5,32”
arr.reverse();
alert(arr.toString()); //outputs “32,5,3,2”
Of course, this is an extra step added to the sorting process, and there is certainly nothing wrong with
creating two comparison functions whenever sorting is necessary. Just keep in mind that whenever an
array is already sorted in one direction, it is much faster to use
reverse()
to sort it in the opposite
direction than it is to call
sort()
once again.
Sorting a One-Column Table
Now you begin the task at hand, sorting a table. The simplest case is to sort a table with just one column
and, therefore, just one data type. The best way to set up a table for sorting is to create a
<thead/>
ele-
ment for the table header rows and a
<tbody/>
element for the rows that contain data:
<table border=”1” id=”tblSort”>
<thead>
<tr>
<th>Last Name</th>
</tr>
</thead>
369
Sorting Tables
15_579088 ch12.qxd 3/28/05 11:40 AM Page 369


JavaScript EditorFree JavaScript Editor     Ajax Editor


©