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]
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
method, which simply reverses the order of the items in an
array, in Chapter 3, “Object Basics.” In this chapter, you learn that the
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
method after the
var arr = [3, 32, 2, 5]
alert(arr.toString()); //outputs “2,3,5,32”
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
to sort it in the opposite
direction than it is to call
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
ment for the table header rows and a
element for the rows that contain data:
<table border=”1” id=”tblSort”>
<th>Last Name</th>
Sorting Tables
15_579088 ch12.qxd 3/28/05 11:40 AM Page 369

JavaScript EditorFree JavaScript Editor     Ajax Editor