array.js 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * 数组 转 Tree
  3. * @param {*} arr
  4. * @param {*} parent
  5. * @param {*} key
  6. * @returns
  7. */
  8. export function arr2Tree(arr = [], parent = "parentId", key = "key") {
  9. // 转换为字典
  10. const dict = arr.reduce((acc, item) => {
  11. return {
  12. ...acc,
  13. [item[key]]: {
  14. ...item,
  15. children: [],
  16. },
  17. };
  18. }, {});
  19. // // 查找顶级结点
  20. // const getRootNode = (node) => {
  21. // const found = arr.filter((x) => node[parentId] === x[key])[0];
  22. // return !found ? dict[node[key]] : getRootNode(found);
  23. // };
  24. // 挂载父子节点
  25. const tree = [];
  26. for (let item of arr) {
  27. const it = dict[item[key]];
  28. const parentNodeId = it[parent];
  29. const parentNode = dict[parentNodeId];
  30. if (!parentNode) {
  31. tree.push(it);
  32. } else {
  33. dict[parentNodeId].children.push(it);
  34. }
  35. }
  36. return [tree, dict];
  37. }
  38. /**
  39. * 深度展平数组
  40. * @param {*} arr
  41. * @returns
  42. */
  43. export function flatten(arr = []) {
  44. return arr.reduce((acc, it) => {
  45. const list = Array.isArray(it) ? flatten(it) : it;
  46. return acc.concat(list);
  47. }, []);
  48. }
  49. /**
  50. * 深度数组去重
  51. * @param {*} arr
  52. */
  53. export function uniq(arr = []) {
  54. const list = flatten(arr);
  55. return list.reduce((acc, it) => {
  56. return acc.indexOf(it) > -1 ? acc : acc.concat(it);
  57. }, []);
  58. }