Sort Array Elements (string with numbers), natural sort

后端 未结 8 1107
你的背包
你的背包 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.

提交回复
热议问题