JS面试题【算法】 - 数组转树

  • 需求:实现数组转树

  • 现有一个数据

      const data = [
    {
      id: 1,
      title: '研发部',
      pid: null,
    },
    {
      id: 2,
      title: '开发部',
      pid: null,
    },
    {
      id: 3,
      title: '市场部',
      pid: null,
    },
    {
      id: 4,
      title: '销售部',
      pid: null,
    },
    {
      id: 5,
      title: '前端研发部',
      pid: 1,
    },
    {
      id: 6,
      title: '后端研发部',
      pid: 1,
    },
    {
      id: 7,
      title: '算法研发部',
      pid: 1,
    },
    {
      id: 8,
      title: '前端开发部',
      pid: 2,
    },
    {
      id: 9,
      title: '后端开发部',
      pid: 2,
    },
    {
      id: 10,
      title: '算法开发部',
      pid: 2,
    },
    ];
    
  • 实现 arrayToTree 函数,将数组转为树

    [
        {
          id: 1,
          pid: null,
          title: '研发部',
          children: [
            { id: 5, title: '前端研发部', pid: 1 },
            { id: 6, title: '后端研发部', pid: 1 },
            { id: 7, title: '算法研发部', pid: 1 },
          ],
        },
        {
          id: 2,
          pid: null,
          title: '开发部',
          children: [
            { id: 8, title: '前端开发部', pid: 2 },
            { id: 9, title: '后端开发部', pid: 2 },
            { id: 10, title: '算法开发部', pid: 2 },
          ],
        },
        { id: 3, title: '市场部', pid: null },
        { id: 4, title: '销售部', pid: null },
    ];
    
  • 实现方法1

    function arrayToTree1(arr) {
        const result = [];
        arr.forEach((item) => {
          if (item.pid === null) {
            result.push(item);
          } else {
            let index = result.findIndex((items) => items.id === item.pid);
            if (index >= 0) {
              result[index].children
                ? result[index].children.push(item)
                : (result[index].children = [item]);
            }
          }
        });
        return result;
    }
    
  • 实现方法2

    function arrayToTree2(array, pid = null) {
        return array.reduce((prev, cur) => {
          if (cur.pid === pid) {
            // 接受每次的返回值
            let index = arrayToTree2(array, cur.id);
            // 判断返回值的长度 如果 返回值有长度 则为数据添加 children 属性
            if (index.length) {
              cur.children = index;
            }
            prev.push(cur);
          }
          return prev;
        }, []);
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值