After using my original Sortable Table for some time now, I’ve noticed something that could be better. Namely, type-awareness! I added the ability to declare each column as containing common type of data like numbers and dates as well as giving the functionality to enable writing custom sort functions.
Source: sortableTable.js
Example: Example
To declare a column as containing numbers, give the associated th, class="number". As you may guess, it basically just parses the string as a float (using parseFloat) before comparing, so “11″ will come after “2″. To sort dates, add class="date" to the th. This simply uses the Date.parse function before comparing.
Now that the “easy” ones were out of the way, I thought about how to give the developer a way to define their own sorting function, since strings, numbers, and dates won’t be the only things that should exist in a sortable table, for example, move ratings.
To do this, add class="custom_sortFunc" to your th where sortFunc is the JavaScript function you want to use to sort. This function should take two arguments and return an integer. The return value should be less than 0 if the first argument should be before the second, 0 if they’re equal sort-wise, and greater than 0 if the first should go after the second.
In the example, you see the following:
var movieRatings = new Array('G', 'PG', 'PG-13', 'R', 'NR');
function movieRatingSort(str1, str2)
{
return movieRatings.indexOf(str1) - movieRatings.indexOf(str2);
}
My movie ratings th has class="custom_movieRatingSort". That’s all!
Note that there is no error checking in the way of checking to see that the custom sort function takes two arguments nor that the return type is an int, so funky things may happen if you give it an invalid function.
