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,

1

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, but the OP said that his table is numerical
Oh. So he did. Oops!"
still doesn't seem to work. I have put the code into jsfiddle here jsfiddle.net/7Ea36
You aren't sorting numbers, you're sorting objects by one of their properties. Use anum = parseInt(a.val,10); and similar for b.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.