一、下载
npm i js-pinyin
二、使用
1.引入库
代码如下(示例):
import Pinyin from 'js-pinyin'
2.代码
代码如下(示例):
// 我的数据格式
contactList: [{
name: '刘筱',
phone: "13200001111",
card: "123123123123123123"
}, {
name: '阿珍',
phone: "13200001112",
card: "123123123123123123"
}, {
name: '王二',
phone: "13200001111",
card: "123123123123123123"
}]
// 函数
sortByFirstLetter(origin) {
// 将目标数据进行排序
origin = origin.sort((pre, next) => Pinyin.getFullChars(pre.name).localeCompare(Pinyin.getFullChars(next.name)))
const newArr = []
origin.map(item => {
// 取首字母
const key = Pinyin.getFullChars(item.name).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
}
3.调用函数
代码如下(示例):
this.contactList2 = this.sortByFirstLetter(this.contactList)
4.输出
代码如下(示例):
[{
"key": "A",
"list": [{
"name": "阿珍",
"phone": "13200001143",
"card": "430321200011112222"
}]
},
{
"key": "L",
"list": [{
"name": "刘筱",
"phone": "13200001111",
"card": "430321200011112222"
}]
},
{
"key": "W",
"list": [{
"name": "王二",
"phone": "13200001111",
"card": "430321200011112222"
}]
}
]