Skip to content

Instantly share code, notes, and snippets.

@GeekEast
Last active October 8, 2021 06:12
Show Gist options
  • Save GeekEast/5f95d86905a7d69b200e803eec000514 to your computer and use it in GitHub Desktop.
Save GeekEast/5f95d86905a7d69b200e803eec000514 to your computer and use it in GitHub Desktop.
Algorithm to transform array into tree
export type Node = { id: number; parentId: number }
const nodes: Node[] = [
{ id: 1, parentId: null },
{ id: 2, parentId: 1 },
{ id: 3, parentId: 1 },
{ id: 4, parentId: 2 },
{ id: 5, parentId: 2 },
{ id: 6, parentId: 3 },
{ id: 7, parentId: 3 }
]
const arrayToTree = (nodes: Node[]) => {
const lookup = {}
const rootNodes = []
for (const node of nodes) {
if (!lookup[node.id]) lookup[node.id] = { ...node, children: [] } // init
lookup[node.id] = { ...lookup[node.id], ...node } // update
const treeNode = lookup[node.id] // reference
const parentId = treeNode.parentId
if (!parentId) rootNodes.push(treeNode)
if (!lookup[parentId]) lookup[parentId] = { children: [] }
lookup[parentId].children.push(treeNode)
}
return rootNodes
}
console.log(JSON.stringify(arrayToTree(nodes), null, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment