鍍金池/ 問(wèn)答/人工智能  Python  HTML/ JavaScript混合字符串排序

JavaScript混合字符串排序

需求:

  1. 一個(gè)數(shù)組
  2. 數(shù)組的每一個(gè)元素都是一個(gè)字符串
  3. 字符串可能為空,即""
  4. 對(duì)該數(shù)組進(jìn)行排序,特殊字符在最前,長(zhǎng)度為0的字符串在最前,即要求3中的例子,然后是下劃線,其他特殊字符串按JS內(nèi)置規(guī)則排序就好

然后是數(shù)字(從小到大),大寫(xiě)字母,小寫(xiě)字母,最后是漢字,字母按照字母表順序排序,漢字按照拼音來(lái)排序

舉例

let a = ["", "A001", "V002", "V003", "_123", "133", "2334", "a001", "v004", "馬龍", "中華", "中國(guó)"]
//排序后
// a = ["", "_123", "133", "2334", "A001", "V002", "V003", "a001", "v004", "馬龍", "中國(guó)", "中華"]

PS:
我去掉了中英文混合的字符串,感覺(jué)加上了會(huì)更復(fù)雜的樣子

回答
編輯回答
膽怯
let arr = ["", "A001", "V002", "V003", "_123", "133", "2334", "大124", "小afaf", "a001", "v004", "馬龍", "中華", "中國(guó)"];
arr.sort(function(a, b) {
    let max_length = Math.max(a.length, b.length),
        compare_result = 0,
        i = 0;
    while(compare_result === 0 && i < max_length) {
        compare_result = compare_char(a.charAt(i), b.charAt(i));
        i++;
    }
    return compare_result;
});

function compare_char(a, b) {
    var a_type = get_char_type(a),
        b_type = get_char_type(b);
    if(a_type === b_type && a_type < 4) {
        return a.charCodeAt(0) - b.charCodeAt(0);
    } else if(a_type === b_type && a_type === 4) {
        return a.localeCompare(b);
    } else {
        return a_type - b_type;
    }
}

function get_char_type(a) {
    var return_code = {
        nul: 0,
        symb: 1,
        number: 2,
        upper: 3,
        lower: 4,
        other: 5
    }
    if(a === '') {
        return return_code.nul; //空
    } else if(a.charCodeAt(0) > 127) {
        return return_code.other;
    } else if(a.charCodeAt(0) > 122) {
        return return_code.symb;
    } else if(a.charCodeAt(0) > 96) {
        return return_code.lower;
    } else if(a.charCodeAt(0) > 90) {
        return return_code.symb;
    } else if(a.charCodeAt(0) > 64) {
        return return_code.upper;
    } else if(a.charCodeAt(0) > 58) {
        return return_code.symb;
    } else if(a.charCodeAt(0) > 47) {
        return return_code.number;
    } else {
        return return_code.symb;
    }
}
console.log(arr);

寫(xiě)的亂了點(diǎn)湊活看吧

2018年9月7日 07:46