为了账号安全,请及时绑定邮箱和手机立即绑定

JavaScript混合字符串排序

JavaScript混合字符串排序

哆啦的时光机 2019-03-20 17:15:57
需求:一个数组数组的每一个元素都是一个字符串字符串可能为空,即""对该数组进行排序,特殊字符在最前,长度为0的字符串在最前,即要求3中的例子,然后是下划线,其他特殊字符串按JS内置规则排序就好然后是数字(从小到大),大写字母,小写字母,最后是汉字,字母按照字母表顺序排序,汉字按照拼音来排序举例let a = ["", "A001", "V002", "V003", "_123", "133", "2334", "a001", "v004", "马龙", "中华", "中国"]//排序后// a = ["", "_123", "133", "2334", "A001", "V002", "V003", "a001", "v004", "马龙", "中国", "中华"]PS:我去掉了中英文混合的字符串,感觉加上了会更复杂的样子
查看完整描述

1 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

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));

        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);

写的乱了点凑活看吧


查看完整回答
反对 回复 2019-04-04
  • 1 回答
  • 0 关注
  • 786 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号