Javascript 总是将空或空排序到底部

Javascript 总是将空或空排序到底部,javascript,sorting,Javascript,Sorting,下面是我从某个我完全忘记的地方提取的一个自然排序函数。我希望对其进行修改,使空值或空值始终排序到底部,而不考虑asc/desc 以下是我现在拥有的: function gridNaturalSorter(a, b) { if(a[sortcol]) a = a[sortcol].replace(/<(?:.|\n)*?>/gm, ''); if(b[sortcol]) b = b[sortcol].replace(/<

下面是我从某个我完全忘记的地方提取的一个自然排序函数。我希望对其进行修改,使空值或空值始终排序到底部,而不考虑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, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
        yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),

        // 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;
}
函数gridNaturalSorter(a,b){ if(a[sortcol]) a=a[sortcol]。替换(//gm',); if(b[sortcol]) b=b[sortcol]。替换(//gm',); 如果(b) b=b.toString().substr(0,15); 如果(a) a=a.toString().substr(0,15); 变量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}/,, hre=/^0x[0-9a-f]+$/i, ore=/^0/,, i=函数{ 返回gridNaturalSorter.sinsensitive&(“”+s).toLowerCase()| |“”+s }, //将所有字符串转换为带空格的字符串 x=i(a)。替换(sre),| |,“”, y=i(b)。替换(sre),| |,“”, //区块/标记化 xN=x.replace(re,'\0$1\0')。replace(/\0$/,'')。replace(/^\0/,'')。split('\0'), yN=y.replace(re,'\0$1\0')。replace(/\0$/,'')。replace(/^\0/,'')。split('\0'), //数字、十六进制或日期检测 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; //首先尝试对十六进制代码或日期进行排序 if(yD) 如果(xDyD)返回1; //通过拆分数字字符串和默认字符串进行自然排序 for(var cLoc=0,numS=Math.max(xN.length,yN.length);cLocoFyNcL) 返回1; } 返回0; }
如果您知道如何实现多个比较器和一个将
null
排序到底的比较器,那就很容易了

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

在这里,我还创建了一个
withComparators
helper函数,它允许将多个比较器组合在一起。如果您理解这段代码,您将能够轻松地为您的特定问题提出自己的解决方案

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

例如

var items=['test',null',test1',test3',null',test4'];
排序(使用比较器(nullsToBottom,textAsc));
//[“测试”、“测试1”、“测试3”、“测试4”、空、空]
函数nullsToBottom(a,b){
返回a==b?0:a==null?1:-1;
}
函数textAsc(a,b){
返回ab);
}
带比较器()的函数{
var比较器=参数;
返回函数(a,b){
var len=比较器。长度,i=0,结果;
对于(;i
你有什么问题吗?你应该在问题中添加代码。出于某种原因,它不会让我发布那么多代码,看起来是一个mod为我添加的。很早之前,你就应该能够知道它是否是空的,因此,只需提前添加
if
并返回
-1
1
,这取决于它是
a
还是
b
不完全相关,但您将使用此函数对哪种数组进行排序?如果一个数组中有所有类型的数据,那么它的设计很糟糕,或者根本不打算进行排序。。。
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;
    };
}