how to sort mixed numeric/alphanumeric array in javascript

前端 未结 4 1442
栀梦
栀梦 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:44

    You could sort it with splitted array by type and check for equality first and then by type.

    var array = ['A1', 'A10', 'A11', 'A12', 'A3A', 'A3B', 'A3', 'A4', 'B10', 'B2', 'F1', '1', '2', 'F3'];
    
    array.sort(function (a, b) {
        var isNumber = function (v) { return (+v).toString() === v; },
            aa = a.match(/\d+|\D+/g),
            bb = b.match(/\d+|\D+/g),
            i = 0,
            l = Math.min(aa.length, bb.length);
    
        while (i < l && aa[i] === bb[i]) {
            i++;
        }
        if (i === l) {
            return aa.length - bb.length;
        }
        if (isNumber(aa[i]) && isNumber(bb[i])) {
            return aa[i] - bb[i];
        }
        return aa[i].localeCompare(bb[i]);
    });
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题