100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Vue 汉字转拼音;根据拼音首字母排序转二维数组;提取拼音首字母排序。

Vue 汉字转拼音;根据拼音首字母排序转二维数组;提取拼音首字母排序。

时间:2023-09-18 05:50:37

相关推荐

Vue 汉字转拼音;根据拼音首字母排序转二维数组;提取拼音首字母排序。

一、基本使用

下载依赖

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']

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。