alpha-numeric sorting
alpha-numeric sorting
I have fields that have values like so: "A10L, A11R, A1L, A2L". I want to sort them on the first alpha character followed by the middle digit or digits. Based on the question here: http://datatables.net/forums/discussion/7546/alpha-numeric-sort I came up with this: (preview shows all this code in one long line and I have no idea how to fix that)
// use sType: "mysort" for any columns you wish to use these routines
jQuery.fn.dataTableExt.oSort['mysort-asc'] = function (a, b) {
var re = new RegExp("^([a-zA-Z]*)([0-9]*)");
var x = re.exec(a);
var y = re.exec(b);
console.log('x is ' + x);
console.log('y is ' + y);
// you might want to force the first portion to lowercase
// for case insensitive matching
// x[1] = x[1].toLowerCase();
// y[1] = y[1].toLowerCase();
if (x[1] > y[1])
return 1;
if (x[1] < y[1])
return -1;
// if you want to force the 2nd part to only be numeric:
x[2] = parseInt(x[2]);
y[2] = parseInt(y[2]);
return ((x[2] < y[2]) ? -1 : ((x[2] > y[2]) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['mysort-desc'] = function (a, b) {
var re = new RegExp("^([a-zA-Z]*)([0-9]*)");
var x = re.exec(a);
var y = re.exec(b);
// you might want to force the first portion to lowercase
// for case insensitive matching
// x[1] = x[1].toLowerCase();
// y[1] = y[1].toLowerCase();
if (x[1] > y[1])
return -1;
if (x[1] < y[1])
return 1;
// if you want to force the 2nd part to only be numeric:
x[2] = parseInt(x[2]);
y[2] = parseInt(y[2]);
return ((x[2] < y[2]) ? 1 : ((x[2] > y[2]) ? -1 : 0));
};
Note that all I changed was the regex. Here's my table definition:
var oDataTable = $('#reporttable').dataTable({
//'aaSorting': [[0, 'asc']],
'aoColumnDefs': [
{'sType': 'mySort', 'aTargets': [0]}
],
'aLengthMenu': [10, 25, 50, 100],
'iDisplayLength': 25,
'bJQueryUI': true,
'bRetrieve': true,
'bAutoWidth': false,
'sScrollX': '100%',
'sPaginationType': 'full_numbers'
});
I'm using DataTables 1.9.4 and jQuery 1.10.2 but this code gives the error :
TypeError: oSort[(("string" + "-") + aaSort[k][1])] is not a function
aoData[b]._aSortData[ aDataSort[l] ]
Any idea what I'm doing wrong?
Answers
Okay, I've upgraded to jQuery 1.11.1, jQuery-ui 1.11.1 and DataTables 1.10.2 and now the error is gone. I've tested the regex function at http://jsfiddle.net/4swm8c92/ and it appears to be working, but my sorting is still wrong. I'm still getting A10L, A10R, A11L, A11R, A1L, A1R in DataTables.
I know I've got to be overlooking something really simple here. Can anyone see what it is?