JQuery sort table rows on column value

Sorting tables dynamically with javascript is often a smooth solution to your sorting problems. I’m here going to put a simple solution that I have been using for a while. I have in no means created this solution – I found it somewhere on the web and now I just want to put it here for easy access.

The table needs to have the following structure for this solution to work:

column1column2column3
value1value2value3
value4value5value6
value7value8value9

The critical parts here is that the table needs an id and a tbody. Without those the sorting will not work

Here is the JQuery code (standard JQuery, no plugins needed)

function sortTable(){
  var rows = $('#mytable 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) {
    $('#mytable').children('tbody').append(row);
  });
}

To sort according to the second column we use ‘.eg(1)’ in row 6 and 7. Second column ‘.eg(3)’ and so on

Here is a JSFiddle of the solution: JQuery sort table rows on column value

Tested on Chrome v44.0.2403.155 (64-bit) and JQuery 1.9.1

Leave a comment ?

21 Comments.

  1. This is nice. I made some slight mods so I could sort by direction and have alternate row colors.

    function sortTable(col,dir){
      var rows = $('#livefeeds tbody  tr').removeClass('row_alt').get();
      
      var t=1;
      if(!dir || dir=='dec') {
    	  t=-1;
      } else if(dir=='asc') {
    	  t=1;
      }
      rows.sort(function(a, b) {
    	  var A = $(a).children('td').eq(col).text().toUpperCase();
    	  var B = $(b).children('td').eq(col).text().toUpperCase();
    	
    	  if(A  B) {
    		return t;
    	  }
    	
    	  return 0;
      });
    
      $.each(rows, function(index, row) {
    	$('#livefeeds').children('tbody').append(row);
    		if( index%2 == 1){
    			$(row).addClass('row_alt');
    		}
    	
      });
    }
    
  2. Ashfaq Ahmad

    Thanks for the share. Helped and Saved my time.

  3. Thanks so much, that saved me a lot of time!

  4. Patrick Kubrat

    thank you very much, this helped me a lot (and I could avoid a postback in asp.net)

    I did some extra things, to enable sorting for more than one row and alternating sort order

        function sortTable(sortCriterium) { //sortCriterium is the row name
            var rows;
            var sortOrder;
            if (retreiveLastSortCriterium() !== sortCriterium) {
                persistSortOrder(1);
            }
            persistLastSortCriterium(sortCriterium);
    
            sortOrder = retreiveSortOrder();
    
            rows = $gridTable.find("tbody tr:gt(0)").get();
            rows.sort(function(a, b) {
                var A, B;
                var $a, $b;
                var $cellA, $cellB;
    
                $a = $(a);
                $b = $(b);
                $cellA = $(a).children('td').eq(sortCriterium);
                $cellB = $(b).children('td').eq(sortCriterium);
    
                switch (sortCriterium) {
    				/* find text for A and B depending on cell  */
    			}
                return A === "" ? 1 : B === "" ? -1 : (A.toUpperCase().toString().localeCompare(B.toUpperCase())) * sortOrder;
            });
    
            $.each(rows, function(index, row) {
                $gridTable.children('tbody').append(row);
            });
            persistSortOrder(sortOrder * -1);
        }
    

    I can now sort several columns and the 2nd click on the same colum orders desc instead of asc. Empty rows come last.
    persist… and retreive access a backing hidden fild to survive asp.net postbacks

  5. I have a table with 8 rows that I sort on column one(1). When I run the code it sorts that data correctly but i end up with the data duplicate(and sorted) 8 times. What am I missing? How do I prevent the data being duplicated and sorted 8 times?

    Thanks.

  6. what returns 1 or -1 do in this case

    • If -1, A is less than B and if 1 B is less than A. It sorts according to alphanumeric order, based on the TD element text

  7. Great Code
    Thanks
    😛

  8. You do not require an id.

    var table = that.closest(‘table’);
    var tbody = table.find(‘tbody’);
    var rows = tbody.find(‘tr’).get();

  9. I would update line #2 to the following to handle nested tables. If not it will attempt to sort the nested table rows.

    var rows = $(‘#livefeeds>tbody>tr’).get();

    In addition if you are attempting to sort a date, you will need to cast it as a date value or sort the text by unix time or a YYYY/MM/DD format.

  10. Very nice. Small and effective. Thumbs up.

  11. from this line
    var rows = $(‘#mytable tbody tr’).get();
    i was getting blank array. please let me know what happen

    • Hi Richa,

      Does your table have id=”mytable”? If not, you need to change the “#mytable” to whatever your table is called

  12. I’m pretty new to jQuery. The code you posted works perfectly but I’m having trouble understanding something. I don’t see anything in the code that explicitly clears the content of before sorting the array of rows. Why doesn’t the append() call applied to each row result in a duplicate of the row being added to the end of ?

    If the object being appended by append() is already part of the target’s content then is it moved from its current location to the end instead of adding a new copy?

    Thanks in advance!

Reply to Patrick Kubrat ¬
Cancel reply


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.