Main Page

Sorting Tables

Sorting Tables
In most applications, sorting lists and tables is a normal procedure that you might use on a daily
basis. When you checking your e-mail, you probably have the table set up to sort by descending
order on the date column, placing the most recent e-mails at the top. It was only a matter of time
before this paradigm made its way onto the Web.
Traditionally, sorting on the Web involves a round-trip to the server with the request indicating
which column should be sorted and in what direction. However, JavaScript enables you to create
the same functionality on the client. Using JavaScript, it’s possible to use sortable tables and also
eliminate the need for costly server-side processing.
The Starting Point — Arrays
Back in Chapter 3, “Object Basics,” you were introduced to the
Array
object and its
sort()
method.
You may remember that the
sort()
method sorts in ascending order by the ASCII character code of
each item, meaning that numbers are also sorted by their string equivalents:
var arr = [3, 32, 2, 5]
arr.sort();
alert(arr.toString()); //outputs “2,3,32,5”
The previous example displays
“2,3,32,5”
when the array is output. Luckily, JavaScript doesn’t
leave you stranded. The
sort()
method can also be given a single argument: a comparison func-
tion to tell the sorting algorithm when one value is greater than, less than, or equal to another value.
A
comparison function
is a function with a specific algorithm. It’s helpful to take a look at a basic
comparison function before continuing with the explanation:
function comparison_function(value1, value2) {
if (value1 < value 2) {
15_579088 ch12.qxd 3/28/05 11:40 AM Page 367


JavaScript EditorFree JavaScript Editor     Ajax Editor


©