GrahamJRoy
GrahamJRoy

Reputation: 1643

Sorting Numbers and Text in Javascript

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,

Upvotes: 0

Views: 158

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

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;

Upvotes: 1

Related Questions