Sort Array of numeric & alphabetical elements (Natural Sort)

后端 未结 8 1066
独厮守ぢ
独厮守ぢ 2020-12-03 14:48

Suppose I have an array

var arr = [1,5,\"ahsldk\",10,55,3,2,7,8,1,2,75,\"abc\",\"huds\"];

and I try sorting it, I get something like ...

8条回答
  •  借酒劲吻你
    2020-12-03 15:03

    // Most natural sorts are for sorting strings, so file2 is sorted before file10.

    If you are mixing in actual numbers you need to sort them to the front of the array, because negative numbers and digits separated by hyphens are a pain to interpret. Strings with leading zeroes need to be careful, so part002 will sort before part010.

    var natSort=function(as, bs) {
        var a, b, a1, b1,
        rx=  /(\d+)|(\D+)/g, rd= /\d/, rz=/^0/;
        if(typeof as=='number' || typeof bs=='number'){
            if(isNaN(as))return 1;
            if(isNaN(bs))return -1;
            return as-bs;
        }
        a= String(as).toLowerCase();
        b= String(bs).toLowerCase();
        if(a=== b) return 0;
        if(!(rd.test(a) && rd.test(b))) return a> b? 1: -1;
        a= a.match(rx);
        b= b.match(rx);
        while(a.length && b.length){
            a1= a.shift();
            b1= b.shift();
            if(a1!== b1){
                if(rd.test(a1) && rd.test(b1)){
                    return a1.replace(rz,'.0')- b1.replace(rz,'.0');
                }
                else return a1> b1? 1: -1;
            }
        }
        return a.length - b.length;
    }
    
    array.sort(natSort)
    

提交回复
热议问题