- 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])// 将分类好的每个对象 合并在一个数组里面
- }
- }
来源: http://www.bubuko.com/infodetail-3343997.html