按拼音首字母进行排序组成新的数组(vue)
数据按首字母相同的组成新的数组,使用拼音(Pinyin)转换
比如想要的效果:
下载
npm install pinyin
代码:
import pinyin from "pinyin";
let studentAllList = [{onLine: true,points: undefined,stDevicemac: "8986032296027887733",stName: "钱里里",stNo: 1054032,stNumber: "8986032342202715675",stShNo: 410,},{onLine: true,points: undefined,stDevicemac: "8886032296027889728",stName: "董小琳",stNo: 1056045,stShNo: 407,},{onLine: true,points: undefined,stDevicemac: "8886032296027889729",stName: "小茗同学",stNo: 1056046,stShNo: 408,},{onLine: true,points: undefined,stDevicemac: "8886032296027889727",stName: "董在德",stNo: 1056049,stShNo: 409,}
];
// 组成首字母排列的数组
const formatPeoArray = (value) =>{return value.reduce((acc, person) => {const firstLetter = pinyin(person.stName[0], {style: pinyin.STYLE_NORMAL,})[0][0].toUpperCase().charAt(0);const foundKey = acc.find((item) => item.key === firstLetter);if (foundKey) {foundKey.list.push(person);} else {acc.push({key: firstLetter,list: [person],});}return acc;}, []).sort((a, b) => a.key.localeCompare(b.key)); // 按字母顺序排序
}
console.log(studentAllList);
console.log(formatPeoArray(studentAllList));