0

I am using a jquery drop down table filter plug in for table filters:

https://github.com/rbayliss/Dropdown-Table-Filter

When I have a column in my table that is numerical however, the numbers are sorted as text, e.g. 1, 10, 100, 2, 20, 200 ...

in the code the sorter looks like:

  if(options.sortOpt) {
    opts.sort(options.sortOptCallback);
  }

I think this is a recursive call to:

sortOptCallback: function(a, b) {
 return a.text.toLowerCase() > b.text.toLowerCase(); 
}, 

how should I amend this so that it will sort numerical fields correctly? I have tried the following:

sortOptCallback: function (a, b) {
  if (isNaN(parseInt(a)) || isNaN(parseInt(b))) {
      return a.text.toLowerCase() > b.text.toLowerCase();
  } else {
      return a > b;
  }
},

Thanks,

GrahamJRoy
  • 1,603
  • 5
  • 26
  • 56
  • possible duplicate of [sort not working with integers?](http://stackoverflow.com/questions/1063007/sort-not-working-with-integers) – Paolo Moretti May 01 '14 at 14:04

1 Answers1

1

Your attempt is almost correct. The only problem is that you are still comparing the elements as strings after having determined that they are numeric. Furthermore, sort callbacks expect:

  • A positive number if a > b
  • A negative number if a < b
  • Zero if they are equal.

With this in mind, try this callback:

if( a == b) return 0;
var anum = parseInt(a,10);
var bnum = parseInt(b,10);
if( isNaN(anum) || isNaN(bnum)) {
    return a.toLowerCase() > b.toLowerCase() ? 1 : -1;
}
return anum > bnum ? 1 : -1;

EDIT: @PaoloMoretti brought my attention to the fact that all your items are numerical. In that case, you can just do this:

return a-b;
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592