Sort Array Elements (string with numbers), natural sort

后端 未结 8 1071
你的背包
你的背包 2020-11-22 10:15

I have an array like;

[\"IL0 Foo\", \"PI0 Bar\", \"IL10 Baz\", \"IL3 Bob says hello\"]

And need to sort it so it appears like;



        
8条回答
  •  时光取名叫无心
    2020-11-22 10:22

    This is called "natural sort" and can be implemented in JS like this:

    function naturalCompare(a, b) {
        var ax = [], bx = [];
    
        a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
        b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });
        
        while(ax.length && bx.length) {
            var an = ax.shift();
            var bn = bx.shift();
            var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
            if(nn) return nn;
        }
    
        return ax.length - bx.length;
    }
    
    /////////////////////////
    
    test = [
        "img12.png",
        "img10.png",
        "img2.png",
        "img1.png",
        "img101.png",
        "img101a.png",
        "abc10.jpg",
        "abc10",
        "abc2.jpg",
        "20.jpg",
        "20",
        "abc",
        "abc2",
        ""
    ];
    
    test.sort(naturalCompare)
    document.write("
    " + JSON.stringify(test,0,3));

    To sort in reverse order, just swap the arguments:

    test.sort(function(a, b) { return naturalCompare(b, a) })
    

    or simply

    test = test.sort(naturalCompare).reverse();
    

提交回复
热议问题