Works for a Living
Works for a Living

Reputation: 1293

sort table alphanumerically with js

I'm trying to modify sorttable.js to add the option to sort alphanumerically.

Right now, if you sort by alpha, strings with numbers in them will sort like this:

If I make it sort numeric, it ignores the alpha characters when sorting. I'm trying to figure out how to combine the two functions to make it sort by both at once. Here are the two functions:

  sort_numeric: function(a,b) {
    aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
    if (isNaN(bb)) bb = 0;
    return aa-bb;
  },
  sort_alpha: function(a,b) {
    if (a[0]==b[0]) return 0;
    if (a[0]<b[0]) return -1;
    return 1;
  },

Could anybody provide any pointers on how I might begin?

Upvotes: 0

Views: 808

Answers (1)

AwokeKnowing
AwokeKnowing

Reputation: 8206

in you function, get the 2 numbers. convert them to strings. figure out which is the longest. add "leading zeros" to the other one, then sort alpha as usual.

Upvotes: 1

Related Questions