JavaScript mixed string sort

demand:

  1. an array
  2. Each element of the
  3. array is a string
  4. The
  5. string may be empty, that is, ""
  6. sort the array with special characters first and strings of length 0 first, that is, the example in requirement 3, followed by underscores. Other special strings can be sorted according to the built-in rules of JS
  7. .

followed by numbers (from small to big), uppercase letters, lowercase letters, and finally Chinese characters, alphabetical order, Chinese characters sorted by pinyin

give an example

let a = ["", "A001", "V002", "V003", "_123", "133", "2334", "a001", "v004", "", "", ""]
//
// a = ["", "_123", "133", "2334", "A001", "V002", "V003", "a001", "v004", "", "", ""]

PS:
I removed the mixed Chinese and English strings and felt that it would be more complicated

.

let arr = ["", "A001", "V002", "V003", "_123", "133", "2334", "124", "afaf", "a001", "v004", "", "", ""];
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));
        iPP;
    }
    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);

the writing is a bit of a mess. Let's take a look at it

Menu