Alpha-Numeric Sort?

Alpha-Numeric Sort?

rmm1613rmm1613 Posts: 10Questions: 0Answers: 0
edited November 2011 in General
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!

Replies

  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    edited December 2011
    you can use regular expressions to easily divide the entry into the alpha and non-alpha portion

    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]
  • rmm1613rmm1613 Posts: 10Questions: 0Answers: 0
    Wow, this is excellent. We will implement and see how it goes. Thank you so much!
This discussion has been closed.