[removed] natural sort of alphanumerical strings

后端 未结 7 1641
抹茶落季
抹茶落季 2020-11-21 10:19

I\'m looking for the easiest way to sort an array that consists of numbers and text, and a combination of these.

E.g.

\'123asd\'
\'19asd\'
\'12345asd\'         


        
7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 10:43

    Imagine an 8 digit padding function that transforms:

    • '123asd' -> '00000123asd'
    • '19asd' -> '00000019asd'

    We can used the padded strings to help us sort '19asd' to appear before '123asd'.

    Use the regular expression /\d+/g to help find all the numbers that need to be padded:

    str.replace(/\d+/g, pad)
    

    The following demonstrates sorting using this technique:

    var list = [
        '123asd',
        '19asd',
        '12345asd',
        'asd123',
        'asd12'
    ];
    
    function pad(n) { return ("00000000" + n).substr(-8); }
    function natural_expand(a) { return a.replace(/\d+/g, pad) };
    function natural_compare(a, b) {
        return natural_expand(a).localeCompare(natural_expand(b));
    }
    
    console.log(list.map(natural_expand).sort()); // intermediate values
    console.log(list.sort(natural_compare)); // result

    The intermediate results show what the natural_expand() routine does and gives you an understanding of how the subsequent natural_compare routine will work:

    [
      "00000019asd",
      "00000123asd",
      "00012345asd",
      "asd00000012",
      "asd00000123"
    ]
    

    Outputs:

    [
      "19asd",
      "123asd",
      "12345asd",
      "asd12",
      "asd123"
    ]
    

提交回复
热议问题