在前端开发过程中,按照汉字首字母排序分组是很常见的操作,比如联系人列表

安装第三方插件    npm i --save js-pinyin  

在需要使用到的vue页面引入  import Pinyin from 'js-pinyin'

具体方法参考以下 sortByFirstLetter 代码块


const originData = ['上饶', '上海', '深圳', '广州', '武汉', '十堰', '天津', '北京']

function sortByFirstLetter(origin) {
    // 将目标数据进行排序
    origin = origin.sort((pre, next) => Pinyin.getFullChars(pre).localeCompare(Pinyin.getFullChars(next)))
    const newArr = []
    origin.map(item => {
        // 取首字母
        const key = Pinyin.getFullChars(item).charAt(0)
        const index = newArr.findIndex(subItem => subItem.key === key)
        if (index < 0) {
            newArr.push({
                key: key,
                list: [item]
            })
        } else {
            newArr[index].list.push(item)
        }
    })
    return newArr
}
console.log(sortByFirstLetter(originData))

[
    { key: 'B', list: ['北京'] },
    { key: 'G', list: ['广州'] },
    { key: 'S', list: ['上海', '上饶', '深圳', '十堰'] },
    { key: 'T', list: ['天津'] },
    { key: 'W', list: ['武汉'] }
]

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐