Sort Array Elements (string with numbers), natural sort

后端 未结 8 1108
你的背包
你的背包 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:32

    Add one more alternative (why not):

    var ary = ["IL0 Foo", "PI0 Bar", "IL10 Hello", "IL10 Baz", "IL3 Bob says hello"];
    
    // break out the three components in to an array
    // "IL10 Bar" => ['IL', 10, 'Bar']
    function getParts(i){
        i = i || '';
        var parts = i.match(/^([a-z]+)([0-9]+)(\s.*)$/i);
        if (parts){
            return [
                parts[1],
                parseInt(parts[2], 10),
                parts[3]
            ];
        }
        return []; // erroneous
    }
    ary.sort(function(a,b){
        // grab the parts
        var _a = getParts(a),
            _b = getParts(b);
    
        // trouble parsing (both fail = no shift, otherwise
        // move the troubles element to end of the array)
        if(_a.length == 0 && _b.length == 0) return 0;
        if(_a.length == 0) return -1;
        if(_b.length == 0) return 1;
    
        // Compare letter portion
        if (_a[0] < _b[0]) return -1;
        if (_a[0] > _b[0]) return 1;
        // letters are equal, continue...
    
        // compare number portion
        if (_a[1] < _b[1]) return -1;
        if (_a[1] > _b[1]) return 1;
        // numbers are equal, continue...
    
        // compare remaining string
        if (_a[2] < _b[2]) return -1;
        if (_a[2] > _b[2]) return 1;
        // strings are equal, continue...
    
        // exact match
        return 0;
    });
    

    jsfiddle example

提交回复
热议问题