how to sort mixed numeric/alphanumeric array in javascript

前端 未结 4 1424
栀梦
栀梦 2021-02-09 03:25

I have a mixed array that I need to sort by number, alphabet and then by digit-

[\'A1\', \'A10\', \'A11\', \'A12\', \'A3A\', \'A3B\', \'A3\', \'A4\', \'B10\', \'         


        
4条回答
  •  既然无缘
    2021-02-09 03:52

    Try this functionality. it give the result which you want exactly

       var arr = ['A1', 'A10', 'A11', 'A12', 'A3A', 'A3B', 'A3', 'A4', 'B10', 'B2', 'F1', '1', '2', 'F3'];
    function sortFn(a, b) {     
        var ax = [], bx = [];
        a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
        b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });        
        while(ax.length && bx.length) {
            var an = ax.shift();
            var bn = bx.shift();
            var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
            if(nn) return nn;
        }
        return ax.length - bx.length;      
    }
    console.log(arr.sort(sortFn));

提交回复
热议问题