2

I have a columns in my table which get generated dynamically. Table got columns like Name, Company etc., It also got column which contains version numbers (1.14.0.2, 1.12.1.0, 1.8.0.1).

I am using library called Sortable for in-place sorting. This is great library which works just out of the box!

It works fine for columns like Name and Company. But it fails for Version Number in some cases. I'm setting data-value to result of

str_replace('.','',$version_number)

But it fails when version numbers are 1.10.0, 1.14, 1.0.1.2 (Special Case)

It should sort like

1.0.1.2
1.10.0
1.14

But it sorts like

1.14
1.0.1.2
1.10.0

Any way I can achieve correct results?

localhost
  • 228
  • 1
  • 11

1 Answers1

1

It sorts like that because it sorts by the data value, which you're setting to a number without the periods.

1.14      --> 114  (smallest)
1.0.1.2   --> 1012
1.10.0    --> 1100 (largest)

If you leave the data-value attribute absent, or leave the periods in the version numbers, it'll sort correctly. As demonstrated in the fiddle below.

https://jsfiddle.net/t7xhkkjc/

Edit

You need to add a custom sorting function to correctly sort version numbers

// Credit for function http://stackoverflow.com/a/7717160/769237
var customTypes = [{
  name: 'version',
  defaultSortDirection: 'descending',
  match: function(a) {
    return a.match(/([1-9]+\.?)+/g);
  },
  compare: function (a, b) {
    var i, cmp, len, re = /(\.0)+[^\.]*$/;
    a = (a + '').replace(re, '').split('.');
    b = (b + '').replace(re, '').split('.');
    len = Math.min(a.length, b.length);
    for( i = 0; i < len; i++ ) {
      cmp = parseInt(a[i], 10) - parseInt(b[i], 10);
      if( cmp !== 0 ) {
        return cmp;
      }
    }
    return a.length - b.length;
  }
}];

So that you don't lose the original sorting types by overriding them

var customAndOriginalTypes = Sortable.types.concat(customTypes);

Sortable.setupTypes(customAndOriginalTypes);

Also, you need to disable the auto initialisation by removing data-sortable from your table. This allows you to add the new sort type prior to adding the sorting functionality to the table.

You can then initialise sorting on the table with

var yourTable = document.querySelector('#your-table');

Sortable.initTable(yourTable);

https://jsfiddle.net/p4w5bup3/

Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108