做通讯录时,每一条数据通常会带有姓名首字母,前台渲染时需要把相同首字母的数据组合到一起,例如,把姓名首字母是A的数据组合到一起,首字母为B的组合到一起 :
const arr = [
    {name: '吕xx', i: 'L'},
    {name: '李xx', i: 'L'},
    {name: '刘xx', i: 'L'},
    {name: '宫xx', i: 'G'},
    {name: '王xx', i: 'W'},
    {name: '张xx', i: 'Z'},
    {name: '本xx', i: 'B'},
    {name: '修xx', i: 'X'},
    {name: '阿xx', i: 'A'}
]
function combineData(arr) {
    let map = {}
    let newArr = []
    arr.forEach(item => {
        const KEY = item['i']
        if (!map[KEY]) {
            map[KEY] = {
                title: KEY,
                items: []
            }
        }
        map[KEY]['items'].push(item)
    })
    for (let key in map) {
        // 是否有字母
        if (map[key]['title'].match(/[A-z]/gi)) {
            newArr.push(map[key])
        }
    }
    newArr.sort((a, b) => {
        return a['title'].charCodeAt(0) - b['title'].charCodeAt(0)
    })
    console.log(newArr)
}
combineData(arr)结果:

知识点:
1、charCodeAt(index)
index(字符串的索引) - 大于等于0 小于字符串长度,默认为0,超出索引 返回NaN
字符串方法,返回的是给定索引处的Unicode编码
"ABC".charCodeAt() // A对应的Unicode编码 65
"ABC".charCodeAt(0) // A对应的Unicode编码 65
"ABC".charCodeAt(1) // B对应的Unicode编码 66
"ABC".charCodeAt(10) // NaN2、charAt(index)
index(字符串索引)
返回指定位置的字符,默认值为0,超出索引,返回空字符串 ''
"ABC".charCodeAt() // 'A'
"ABC".charCodeAt(0) // 'A'
"ABC".charCodeAt(1) // 'B'
"ABC".charCodeAt(10) // ''
                









