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

Posted 不如吃茶去v

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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])//将分类好的每个对象 合并在一个数组里面
    }
}

以上是关于JS首字母进行分类合并加排序的主要内容,如果未能解决你的问题,请参考以下文章