0

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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
lostInTheTetons
  • 1,162
  • 1
  • 13
  • 23
  • 1
    There is a plugin for jQuery called [DataTables](https://datatables.net/). Software development is about code reuse and when it is wise to use or not use a plugin. In your case, a plugin is advised. – Mr. Polywhirl Nov 18 '16 at 14:40
  • [Sort array of objects by string property value in JavaScript](http://stackoverflow.com/a/35092754/215552) – Heretic Monkey Nov 18 '16 at 14:57

1 Answers1

3

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;
    };
asfez
  • 184
  • 1
  • 8
  • How could I do this if I'm getting all of the info to fill the table from the database? Just set myNumber to an empty number? – lostInTheTetons Nov 18 '16 at 14:43
  • Or simply `parseInt(res, 10)` Don't forget the radix... That number will be parsed as `10` instead of `12` because that is an octal number (Leading `0`). – Mr. Polywhirl Nov 18 '16 at 14:43
  • You should transform your sort key by this way. – asfez Nov 18 '16 at 14:48
  • ***Note:*** [`Number.parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseInt) will not work on IE or Safari -- Use [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt). – Mr. Polywhirl Nov 18 '16 at 14:48
  • http://codepen.io/tetonhiker/pen/rWjNWq here is a demo and you can see how the number column isn't sorting correctly – lostInTheTetons Nov 18 '16 at 14:48