utils.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * @Autor: hlb
  3. * @Date: 1970-01-01 08:00:00
  4. * @LastEditors: hlb
  5. * @LastEditTime: 2020-11-25 18:37:34
  6. * @description: 工具
  7. */
  8. import toPinyin from "./toPinyin";
  9. /**
  10. * 根据拼音首字母筛选排序分组
  11. * @param {Array} arr 原数组
  12. * @param {String} key 原数组需要筛选的字段
  13. * @returns {Array} 返回一个[{name: A,value: []}] 格式的二维数组
  14. */
  15. export function getGroupByPinyin(arr, key = 'name') {
  16. if(!arr) return
  17. // 获取A-Z字母数组
  18. let keys = [...Array(26).keys()].map((i) => String.fromCharCode(i + 65));
  19. arr = arr.map((n) => ({
  20. ...n,
  21. py: toPinyin.chineseToInitials(
  22. toPinyin.chineseToPinYin(n[key].substr(0, 1))
  23. ),
  24. }));
  25. let group = [];
  26. for (const i of keys) {
  27. // 新数组一级结构,可自行修改
  28. let item = {
  29. name: i,
  30. value: [],
  31. };
  32. for (const j of arr) {
  33. if (j.py === i) {
  34. item.value.push(j);
  35. }
  36. }
  37. if (item.value.length > 0) {
  38. item.value.sort((a, b) => a[key].localeCompare(b[key]));
  39. group.push(item);
  40. }
  41. }
  42. return group;
  43. }