一、基本使用
下载依赖
cnpm i js-pinyin
使用:
import Pinyin from 'js-pinyin';
console.log(Pinyin.getFullChars('管理员')); // GuanLiYuan
console.log(Pinyin.getCamelChars('管理员')); // GLY;
二、根据拼音首字母排序转二维数组
原数组:
const newIndexList = [
{ username: '张三' },
{ username: '张四' },
{ username: '李四' },
{ username: '王五' }
[
根据拼音首字母排序转二维数组:
// 创建一个空对象,用于存储分组
const grouped = {};
// 遍历原始数组并进行分组
newIndexList.forEach(item => {
const username = item.username;
const pinyin = Pinyin.getFullChars(username);
const firstLetter = pinyin.charAt(0).toUpperCase();
if (!grouped[firstLetter]) {
grouped[firstLetter] = [];
}
grouped[firstLetter].push(item);
});
// 将分组后的对象转换为数组
// 获取分组后的键(首字母),并排序
const groupedKeys = Object.keys(grouped).sort();
// 创建一个按首字母排序的结果数组
const sortedGroupedArray = groupedKeys.map(key => grouped[key]);
return sortedGroupedArray
/*
[
[
{username: '王五'},
],
[
{username: '李四'},
],
[
{username: '张三'},
{username: '张四'},
]
]
*/
三、提取拼音首字母排序:
// 创建一个空数组,用于存储拼音首字母
const pinyinFirstLetters = [];
// 遍历原始数组并获取拼音首字母
newIndexList.forEach(item => {
const username = item.username;
const pinyin = Pinyin.getFullChars(username);
const firstLetter = pinyin.charAt(0).toUpperCase();
if (!pinyinFirstLetters.includes(firstLetter)) {
pinyinFirstLetters.push(firstLetter);
}
});
return pinyinFirstLetters.sort() // ['W','L','Z']