Zack Macomber Zack Macomber - 5 months ago 18
Javascript Question

How to sort date columns that have empty cells

I'm using the sorttable.js script found at http://www.kryogenix.org/code/browser/sorttable/

One problem I'm having is that sorting isn't working on my date columns that have a mix of empty cells and dates. My dates are in "MM/DD/YYYY" format.

From what I can see, the sort is occurring here in the script:

sort_mmdd: function(a,b) {
mtch = a[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt1 = y+m+d;
mtch = b[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt2 = y+m+d;
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
}


What I can't figure out is how to make the blank cells either go all to the top or to the bottom when a sort occurs on the column.

Any ideas on how I can go about doing this?

Answer

I figured out how to get the dates to work alongside blank cells (see below).

Ultimately tested "mtch" before using it later...

sort_mmdd: function(a,b) {

    mtch = a[0].match(sorttable.DATE_RE);

    if ((mtch == null) || (mtch == undefined)) {
        y = 0; d = 0; m = 0;
    }
    else {
        y = mtch[3]; d = mtch[2]; m = mtch[1];
    }

    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;

    mtch = b[0].match(sorttable.DATE_RE);

    if ((mtch == null) || (mtch == undefined)) {
        y = 0; d = 0; m = 0;
    }
    else {
        y = mtch[3]; d = mtch[2]; m = mtch[1];
    }

    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
}