18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Sorting Tables<br />

}<br />

if (iNum1 < iNum2) {<br />

return –1;<br />

} else if (iNum1 > iNum2) {<br />

return 1;<br />

} else {<br />

return 0;<br />

}<br />

If you apply this comparison function to the earlier example, the correct result is returned:<br />

var arr = [3, 32, 2, 5]<br />

arr.sort(compareIntegers);<br />

alert(arr.toString()); //outputs “2,3,5,32”<br />

This example now outputs the numbers in correct order (2, 3, 5, 32).<br />

The reverse() method<br />

You were introduced to the reverse() method, which simply reverses the order of the items in an<br />

array, in Chapter 3, “Object Basics.” In this chapter, you learn that the reverse() method is an essential<br />

part of sorting.<br />

So, if you use a comparison function that sorts in ascending order, you can easily change the sort to<br />

descending order by using the reverse() method after the sort() method:<br />

var arr = [3, 32, 2, 5]<br />

arr.sort(compareIntegers);<br />

alert(arr.toString()); //outputs “2,3,5,32”<br />

arr.reverse();<br />

alert(arr.toString()); //outputs “32,5,3,2”<br />

Of course, this is an extra step added to the sorting process, and there is certainly nothing wrong with<br />

creating two comparison functions whenever sorting is necessary. Just keep in mind that whenever an<br />

array is already sorted in one direction, it is much faster to use reverse() to sort it in the opposite<br />

direction than it is to call sort() once again.<br />

Sorting a One-Column Table<br />

Now you begin the task at hand, sorting a table. The simplest case is to sort a table with just one column<br />

and, therefore, just one data type. The best way to set up a table for sorting is to create a element<br />

for the table header rows and a element for the rows that contain data:<br />

<br />

<br />

<br />

Last Name<br />

<br />

<br />

369

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!