[removed] natural sort of alphanumerical strings

后端 未结 7 1481
抹茶落季
抹茶落季 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:53

    To compare values you can use a comparing method-

    function naturalSorter(as, bs){
        var a, b, a1, b1, i= 0, n, L,
        rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
        if(as=== bs) return 0;
        a= as.toLowerCase().match(rx);
        b= bs.toLowerCase().match(rx);
        L= a.length;
        while(ib1? 1:-1;
            }
        }
        return b[i]? -1:0;
    }
    

    But for speed in sorting an array, rig the array before sorting, so you only have to do lower case conversions and the regular expression once instead of in every step through the sort.

    function naturalSort(ar, index){
        var L= ar.length, i, who, next, 
        isi= typeof index== 'number', 
        rx=  /(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.(\D+|$))/g;
        function nSort(aa, bb){
            var a= aa[0], b= bb[0], a1, b1, i= 0, n, L= a.length;
            while(ib1? 1: -1;
                }
            }
            return b[i]!= undefined? -1: 0;
        }
        for(i= 0; i

提交回复
热议问题