js通讯录按照首字母排序

this._sortFriend(data.data)
_chineseToEnglish(c) {
    var idx = -1;
    var MAP = 'ABCDEFGHJKLMNOPQRSTWXYZ';
    var boundaryChar = '驁簿錯鵽樲鰒餜靃攟鬠纙鞪黁漚曝裠鶸蜶籜鶩鑂韻糳';
    if (!String.prototype.localeCompare) {
        throw Error('String.prototype.localeCompare not supported.');
    }
    if (/[^\u4e00-\u9fa5]/.test(c)) {
        return c;
    }
    for (var i = 0; i < boundaryChar.length; i++) {
        if (boundaryChar[i].localeCompare(c, 'zh-CN-u-co-pinyin') >= 0) {
            idx = i;
            break;
        }
    }
    return MAP[idx];
},
//获取第一个字母
_getFirstUpperChar(str) {
    var string = String(str);
    var c = string[0];
    if (/[^\u4e00-\u9fa5]/.test(c)) {
        return c.toUpperCase();
    } else {
        return this._chineseToEnglish(c);
    }
},
//排序
_sortFriend(list) {
    let that = this
    let map = {}
    map['#'] = [];
    var c = 'A'.charCodeAt();
    for (; c <= 'Z'.charCodeAt(); c++) {
        map[String.fromCharCode(c)] = [];
    }
    var firstCharUpper;
    list.forEach(function (item) {
        firstCharUpper = that._getFirstUpperChar(item.name);
        if (map.hasOwnProperty(firstCharUpper)) {
            map[firstCharUpper].push(item);
        } else {
            map['#'].push(item);
        }
    });
    for (let a in map) {
        if (!map[a].length) {
            delete map[a]
        }
    }
    return map;
}

记录小功能

你可能感兴趣的:(vue,node,js,javascript,原型模式)