Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

将给定的数组从顶级分类递归查找子分类,最终构建一个树状数组 #212

Open
lgwebdream opened this issue Jul 6, 2020 · 3 comments
Labels
算法 teach_tag

Comments

@lgwebdream
Copy link
Owner

/*
 *数组:[{id:1, parentId: 0}, {id:2, parentId:1},{id:3, parentId:1}]
 *输出结果:[{id:1, parentId: 0,children:[{id:2, parentId:1},{id:3, parentId:1}]}]
 *说明:parentId为0 的是根节点
 */
@lgwebdream lgwebdream added the 算法 teach_tag label Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@523451928
Copy link

var arr = [{ id: 1, parentId: 0 }, { id: 2, parentId: 1 }, { id: 3, parentId: 1 }]
function buildTree(arr) {
  const result = []
  const copyArr = [...arr]
  const map = {}
  copyArr.forEach((item) => {
    map[item.id] = item
  })
  for (const key in map) {
    const item = map[key]
    if (item.parentId === 0) {
      result.push(item)
    } else {
      const parent = map[item.parentId]
      parent.children = parent.children || []
      parent.children.push(item)
    }
  }
  return result
}
buildTree(arr)

@AAA611
Copy link

AAA611 commented Aug 31, 2022

代码

function fn(arr) {
  let parents = []
  const len = arr.length

  for (let i = 0; i < len; i++) {
    parents[arr[i].id] = arr[i]
  }

  let parent
  for (let i = 0; i < arr.length; i++) {
    parent = parents[arr[i].parentId]
    if (!parent) continue
    if (parent.children) {
      parent.children.push(arr[i])
    } else {
      parent.children = [arr[i]]
    }
    arr.splice(i, 1)
    i--
  }

  return arr
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 teach_tag
Projects
None yet
Development

No branches or pull requests

3 participants