maikunari
maikunari

Reputation: 109

jquery Tablesorter - natural sort order?

I've looked through all the answers listed for tablesorter but can't find what I'm looking for.

I have a table which I'm trying to sort, one column contains product model numbers which include both letters and numbers, the problem is that it sorts alphabetically but not with the numbers in their proper order. For example the sorted column comes out like this:

STRB 18, STRB 19, STRB 2, STRB 20, STRB 23 - you get the idea.

I've gathered that I need this column to sort in natural order, but I've not got any js chops to do this with. If anybody could point me in the right direction I would be very grateful!

Upvotes: 2

Views: 2974

Answers (3)

Dan Appleyard
Dan Appleyard

Reputation: 7445

The jquery tablesorter plugin offers the ability to write your own parser.

Check out the example and give it a shot!

http://tablesorter.com/docs/example-parsers.html

Upvotes: 2

user187291
user187291

Reputation: 53940

taken from some old code of mine

compare = {
    natural: function(a, b) {
        function prepare(s) {
            var q = [];
            s.replace(/(\D)|(\d+)/g, function($0, $1, $2) {
                q.push($1 ? 1 : 2);
                q.push($1 ? $1.charCodeAt(0) : Number($2) + 1)
            });
            q.push(0);
            return q;
        }
        var aa = prepare(a), bb = prepare(b), i = 0;
        do {
            if(aa[i] != bb[i])
                return aa[i] - bb[i];
        } while(aa[i++] > 0);
        return 0;
    }
}

example of use

test = ['img100b', 'img21', 'img18', 'img100a', 'img1', 'img2']
console.log(test.sort(compare.natural))

Upvotes: 3

Limey
Limey

Reputation: 2772

Not sure what you mean by "natrual" order, but I am guessing you mean that strb 2 would be before strb 18.

The order you have above is correct for strings. if you want to sort by the number portion (assuming all the strb's are always the same) you will have to do a substring to get the number only and then sort the data.

I would also NOT do this in javascript. Let your database work for you and let it handle the order of the data. It will save you a lot of pain.

Upvotes: -2

Related Questions