JS首字母进行分类合并加排序

let array = ['fds', 'ewfg1', 'cvd', 'ew', 'qer', 'jjh', 'rth', 'asd', 'vsd', 'tteh', 'fxv'];
let map = {};
for(let i = 0; i < 26; i++){
    const key = String.fromCharCode(65 + i) //A-Z赋给key当作键
    map[key] = {
        title: key,
        items: []
    }
    array.map((v,k)=>{      //遍历数组
        let firstIndex = v.charAt(0).toUpperCase();//首字母
        if(firstIndex.toUpperCase() == String.fromCharCode(65+i)){//统一转成大写进行逐个判断
            map[key].items.push(v)//push进相对应的数组里头
        }
    })
    // //如果当前的数组里头为空,则跳过。
    if(map[key].items === undefined || map[key].items.length == 0){
        continue;
    }else{
        this.newArr.push(map[key])//将分类好的每个对象 合并在一个数组里面
    }
}
posted @ 2019-12-22 09:53  不如吃茶去v  阅读(909)  评论(0编辑  收藏  举报