Teton-Coder Teton-Coder - 14 days ago 5
Javascript Question

How can I sort a data table numerically with jquery

I have a HTML table and the jQuery code to sort the table alphabetically but I can't figure out how to order one of the columns numerically. It is only ordering the numeric column by the first number and not the longer numbers. So 99 shows up at the top and not 9340.

$('thead th').each(function(column) {
$(this).addClass('sortable').click(function(){
var findSortKey = function($cell) {
return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
};
var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;
//step back up the tree and get the rows with data
//for sorting
var $rows = $(this).parent().parent().parent().find('tbody tr').get();
//loop through all the rows and find
$.each($rows, function(index, row) {
row.sortKey = findSortKey($(row).children('td').eq(column));
});
//compare and sort the rows alphabetically
$rows.sort(function(a, b) {
if (a.sortKey < b.sortKey) return -sortDirection;
if (a.sortKey > b.sortKey) return sortDirection;
return 0;
});
//add the rows in the correct order to the bottom of the table
$.each($rows, function(index, row) {
$('tbody').append(row);
row.sortKey = null;
});
//identify the column sort order
$('th').removeClass('sorted-asc sorted-desc');
var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');
sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');
//identify the column to be sorted by
$('td').removeClass('sorted')
.filter(':nth-child(' + (column + 1) + ')')
.addClass('sorted');
});
});
function filterDataTable(selector,query){
query = $.trim(query);
query = query.replace(/ /gi, '|');
$(selector).each(function(){
($(this).text().search(new RegExp(query, "i")) < 0 ) ? $(this).hide().removeClass('visibile') : $(this).show().addClass('visible');
});
}
$('tbody tr').addClass('visible');
$("#filter").keyup(function(event){
if(event.keyCode == 27 || $(this).val() == ''){
$(this).val('');
$('tbody tr').removeClass('visible').show().addClass('visible');
}else {
filter('tbody tr', $(this).val());
}
});
$('#filter').show();


I did some googling to see if a question was asked like this but I couldn't find one to fit what I needed exactly. Most of them told others to use plugins but I don't want to add any plugins. I want to have my own sorting code. Thanks.

Answer

You can fill your number with 0 to get a sortable string :

var myNumber = 12;
var filler = "00000000000";
var res = filler.substr(0, filler.length - myNumber.toString().length) + myNumber; 

Normally, res = 0000000012

You can have your number back if needed with parseInt(res,10)

This code is working in your snippet.

 var findSortKey = function($cell) {
      var sk = $cell.find('.sort-key').text().toUpperCase() + ' ' +  $cell.text().toUpperCase();
      var ik = parseInt(sk,10);
      return ik != NaN ? ik : sk;
    };
Comments