user3760531 user3760531 - 4 months ago 26
jQuery Question

Sorting versioning info in tablesorter.js

I was wondering if there was a way to sort several version numbers (like

1.8.5
or
2.7.1
).

Their length is not always the same (
1.8
is greater than
1.7.1
for instance).

Is there a way to do that?

Answer

Try this generic version parser (demo):

$(function () {

    /************************
      Generic version parser
     ************************/
    // set the number of blocks
    // e.g. 2 = 000.000
    // and 3 = 000.000.000
    var blocks = 3,
        // length of each block
        // 3 = 000
        // 4 = 0000
        digits = 3;

    $.tablesorter.addParser({
        id: "versions",
        is: function (s) {
            return false;
        },
        format: function (s, table) {
            var i,
            a = s ? s.split(".") : [],
                r = "",
                d = new Array(digits + 1).join('0');

            for (i = 0; i < blocks; i++) {
                r += (d + (a[i] || 0)).slice(-digits);
            }
            return s ? $.tablesorter.formatFloat(r, table) : s;
        },
        type: "numeric"
    });

    $('table').tablesorter({
        theme: 'blue',
        headers: {
            3: { sorter: "versions" }
        }
    });

});
Comments