始终从底部为空或null排序



下面是我从我完全忘记的地方提取的一个自然排序函数。我想修改它,使空值或null值总是排序到底,而不管asc/desc。

以下是我现在拥有的:

function gridNaturalSorter(a, b) {      
    if(a[sortcol])
        a = a[sortcol].replace(/<(?:.|n)*?>/gm, '');
    if(b[sortcol]) 
        b = b[sortcol].replace(/<(?:.|n)*?>/gm, '');
    if(b)
        b = b.toString().substr(0, 15);
    if(a)
        a = a.toString().substr(0, 15);
    var re = /(^([+-]?(?:0|[1-9]d*)(?:.d*)?(?:[eE][+-]?d+)?)?$|^0x[0-9a-f]+$|d+)/gi, 
        sre = /(^[ ]*|[ ]*$)/g,
        dre = /(^([w ]+,?[w ]+)?[w ]+,?[w ]+d+:d+(:d+)?[w ]?|^d{1,4}[/-]d{1,4}[/-]d{1,4}|^w+, w+ d+, d{4})/,
        hre = /^0x[0-9a-f]+$/i,
        ore = /^0/,
        i = function(s) { 
            return gridNaturalSorter.insensitive && (''+s).toLowerCase() || ''+s 
        },
        // convert all to strings strip whitespace
        x = i(a).replace(sre, '') || '',
        y = i(b).replace(sre, '') || '',
        // chunk/tokenize
        xN = x.replace(re, '$1').replace(/$/,'').replace(/^/,'').split(''),
        yN = y.replace(re, '$1').replace(/$/,'').replace(/^/,'').split(''),
        // numeric, hex or date detection
        xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
        yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null,
        oFxNcL, oFyNcL;
        // first try and sort Hex codes or Dates
        if (yD)
            if ( xD < yD ) return -1;
        else if ( xD > yD ) return 1;
        // natural sorting through split numeric strings and default strings
        for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
            // find floats not starting with '0', string or 0 if not defined (Clint Priest)
            oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
            oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
            // handle numeric vs string comparison - number < string - (Kyle Adams)
            if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { 
                return (isNaN(oFxNcL)) ? 1 : -1; 
            }
            // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
            else if (typeof oFxNcL !== typeof oFyNcL) {
                oFxNcL += '';
                oFyNcL += '';
            }
            if (oFxNcL < oFyNcL) 
                return -1;
            if (oFxNcL > oFyNcL) 
                return 1;
        }
    return 0;
}

如果你知道如何实现多个比较器和一个将null排序到底的比较器,那就很容易了。

要实现多个比较器,只需要返回第一个不返回0的比较器的结果。

在这里,我还创建了一个withComparators辅助函数,它允许将多个比较器组合在一起。如果你理解了这段代码,你将能够很容易地为你的特定问题找到自己的解决方案。

请注意,您的gridNaturalSorter函数是一个比较器,就像我的示例中的nullsToBottom一样

例如

var items = ['test', null, 'test1', 'test3', null, 'test4'];

items.sort(withComparators(nullsToBottom, textAsc));
//["test", "test1", "test3", "test4", null, null]

function nullsToBottom(a, b) {
    return a === b? 0 : a === null? 1 : -1;
}
function textAsc(a, b) {
    return a < b? -1 : +(a > b);
}
function withComparators() {
    var comparators = arguments;
    return function (a, b) {
        var len = comparators.length, i = 0, result;
        for (; i < len; i++) {
            result = comparators[i](a, b);
            if (result) return result;
        }
        return 0;
    };
}

最新更新