jQuery: sorting tables

Sorting a table is easy with jQuery, provided that you know how to use the JavaScript sort() function of the Array object. In fact, this function accepts another function as its parameter. With this anonymous function, which in turn accepts two parameters, you can compare all the items of an array and return a new array sorted following the criteria specified here. Don't be surprised if the entire jQuery code depends on that! Now let's get to work. Suppose that we have a table containing a column with a series of web sites. You want the table be sorted following the alphabetical order of these sites. Here's the jQuery code:

$(document).ready(function() {

  $('#by-site').click(function(e) {
    var html = [];
    var cleaned = [];
    var index = -1;
    $('#test tr').not(':first').each(function() {
      var $tr = $(this);
    for(var i = 0; i < html.length; i += 1) {
      var bit = html[i];
      var clean = bit.replace(/^\s+|\s+$/g, '');
    var sorted = cleaned.sort(function(a, b) {
      return a.charAt(4) > b.charAt(4);
    $('#test tr').not(':first').each(function() {
       index += 1;


This code performs the following operations:

  1. it loops through all the table rows (except the first one that contains the table headers) and collects the HTML content of each row in the html array
  2. it creates the cleaned array which contains a sanitized version of the HTML content of each row
  3. it sorts the cleaned array calling the sort() function and using the first character of each cell's content as a comparison term
  4. it loops again through all the table rows (except the first one that contains the table headers) and replace their content with the contents of the previously sorted cleaned array.

You can see a demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.