jQuery: sorting tables alphabetically

Sorting a table alphabetically is easy with jQuery, because everything works thanks to the core JavaScript sort() function which will take care of ordering table cells for us. This function accepts a callback function by which we can define our sorting method. In turn, this callback function accepts two values as its parameters. The sort() function works with arrays, so we have to turn our elements into an array first.

Suppose that we have a table containing two columns. In the first column are listed the titles of some famous movies, while in the second their corresponding directors. Our HTML structure will look like this:

<table summary="Movies" id="movies">
<caption>Movies</caption>

<thead>

 <tr>
 
  <th scope="col"><
    a href="#" id="title">Title</a>
  </th>
  <th scope="col">
    <a href="#" id="director">Director</a>
  </th>
 
 </tr>

</thead>

<tbody>

   <tr>
 
  <td>Ghosts of Mars</td>
  <td>John Carpenter</td> 
 </tr>
 
 <!--other movies-->
</tbody>
</table>

When a user clicks on the first link, we want the table to be sorted by title, whereas when a user clicks on the second link, we want that table to be sorted by director's name. Here's our jQuery code:

$('#movies #title').click(function(e) {
  
    var rows = $('#movies tbody  tr').get();
    
    
    rows.sort(function(a, b) {
    
      var A = $(a).children('td').eq(0).text().toUpperCase();
      var B = $(b).children('td').eq(0).text().toUpperCase();
      
      if(A < B) {
        return -1;
      }
      
      if(A > B) {
        return 1;
      }
      
      return 0;     
    
    
    });
    
    
    
    
    
    
    $.each(rows, function(index, row) {
    
      $('#movies').children('tbody').append(row);
      
          
    
    
    });
  
  
    e.preventDefault();
  
  });
  
  
  $('#movies #director').click(function(e) {
  
    var rows = $('#movies tbody  tr').get();
    
    
    rows.sort(function(a, b) {
    
      var A = $(a).children('td').eq(1).text().toUpperCase();
      var B = $(b).children('td').eq(1).text().toUpperCase();
      
      if(A < B) {
        return -1;
      }
      
      if(A > B) {
        return 1;
      }
      
      return 0;     
    
    
    });
    
    
    
    
    
    
    $.each(rows, function(index, row) {
    
      $('#movies').children('tbody').append(row);
      
          
    
    
    });
  
  
    e.preventDefault();
  
  });

Table rows are first converted into a DOM NodeList by using the get() method, so that we're sure that we're dealing with an array-like structure. Then we take into account only the cells which belong to the selected column by using the eq() method. In this case, 0 means column 1 and 1 means column 2. We pass all this data to the sort() function, which will actually sort the text of each cell after such text has been capitalized. Finally, we use a $.each() loop to iterate through the newly sorted array and append the rows in the specified order. You can see a demo below.

Demo

Live demo

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

3 thoughts on “jQuery: sorting tables alphabetically”

  1. out of curiosity; doesnt it make sense to use something like jqTableKit or tableSorter instead?

  2. Yes indeed! It makes much more sense, but generally I like to prefer simpler solutions, especially when I have to do only simple tasks like this. Actually, a plugin is always an expensive solution in terms of performance, and this is true when all you have to do is simply sorting a table alphabetically. For more complex sorting, the plugins you've mentioned are just great, but for this, it's like killing a fly with a bazooka. :-)

Leave a Reply

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