Sort Array Elements (string with numbers), natural sort

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

    You could do a regex like this to get non-numeric and numeric parts of the string:

    var s = "foo124bar23";
    s.match(/[^\d]+|\d+/g)
    

    returns: ["foo", "124" , "bar" , "23"]

    Then in your compare function you can iterate through the parts of the two strings comparing them part-by-part. The first non-matching part determines the result of the overall comparison. For each part, check if the part starts with a digit and if so parse it as a number before doing the comparison.

    0 讨论(0)
  • 2020-11-22 10:49
    var re = /([a-z]+)(\d+)(.+)/i;
    var arr = ["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"];
    var order = arr.sort( function(a,b){
        var ma = a.match(re),
            mb = b.match(re),
            a_str = ma[1],
            b_str = mb[1],
            a_num = parseInt(ma[2],10),
            b_num = parseInt(mb[2],10),
            a_rem = ma[3],
            b_rem = mb[3];
        return a_str > b_str ? 1 : a_str < b_str ? -1 : a_num > b_num ? 1 : a_num < b_num ? -1 : a_rem > b_rem;  
    });
    
    0 讨论(0)
提交回复
热议问题