Alpha-Numeric Sort?
Alpha-Numeric Sort?
Hello All -
We have a data set that will return data in the following manor:
9613
9711
H702
H701
604
605
G101
G100
We need a custom sort that will order these in a alpha-numeric order. The groups that are by alpha should be sorted by numeric within the alpha group.
The expected result from the data above would be:
604
605
9613
9711
G100
G101
H699
H701
H702
Any help would be much appreciated!
We have a data set that will return data in the following manor:
9613
9711
H702
H701
604
605
G101
G100
We need a custom sort that will order these in a alpha-numeric order. The groups that are by alpha should be sorted by numeric within the alpha group.
The expected result from the data above would be:
604
605
9613
9711
G100
G101
H699
H701
H702
Any help would be much appreciated!
This discussion has been closed.
Replies
the exec runs the inputs (a, and then b) through the regular expression and returns an array. index 0 contains the full match, index 1 contains the first portion (the first parentheses), index 2 contains the rest of the input (the second parentheses).
the first test just compares the alpha portions (one or both may be an empty string). if the alpha portions are the same, then compare the second portion
[code]
// 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]*)(.*)");
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));
};
jQuery.fn.dataTableExt.oSort['mysort-desc'] = function(a,b) {
var re = new RegExp("^([a-zA-Z]*)(.*)");
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));
};
[/code]
Here is some debugger console code showing the results of a few trial runs on the regular expression object above:
[code]
~ re = new RegExp("^([a-zA-Z]*)(.*)");
/^([a-zA-Z]*)(.*)/
~ re.exec(500);
["500", "", "500"]
~ re.exec("sdf500");
["sdf500", "sdf", "500"]
~ re.exec("sdf500.j32jf");
["sdf500.j32jf", "sdf", "500.j32jf"]
[/code]