一、基本使用
下载依赖
cnpm i js-pinyin
使用:
import Pinyin from 'js-pinyin';
console.log(Pinyin.getFullChars('管理员')); // GuanLiYuanconsole.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']