const arr = [
{
id: 1,
name: 'teste',
},
{
id: 2,
name: 'teste',
dependsOn: 1,
},
{
id: 3,
name: 'teste',
dependsOn: 1,
},
{
id: 4,
name: 'teste',
},
{ id: 5, name: 'dasdas', dependsOn: 2 },
]
const treeTo = [
{
id: 1,
name: 'teste',
children: [
{
id: 2,
name: 'teste',
children: [],
},
{
id: 3,
name: 'teste',
children: [
{
id: 5,
name: 'teste',
children: [],
},
],
},
],
},
{
id: 4,
name: 'teste',
},
]
I need a function to generate the tree below based on the array
function buildTree(arr, parentId = null) {
return arr
.filter((item) => item.dependsOn === parentId)
.map((item) => ({
...item,
children: buildTree(arr, item.id),
}))
}
i’ve tried something like that, but I’m not that good in recursions
2
Answers
You don’t need recursion here, just make a map of the items by id and add children to appropriate parents.
That will give you O(n) instead of O(n^2) time complexity.
If you want to keep your existing function you could also just change your filter condition to include all root level items.