skip to Main Content
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


  1. 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.

    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 nodes = arr.reduce((r, {dependsOn, ...item}) => (item.children = [], r[item.id] = item, r), {});
    const result = arr.reduce((r, {dependsOn: pid, id}) => ((pid ? nodes[pid].children : r).push(nodes[id]), r), []);
    console.log(result);
    .as-console-wrapper{min-height:100%!important}
    Login or Signup to reply.
  2. If you want to keep your existing function you could also just change your filter condition to include all root level items.

    function buildTree(arr, parentId = null) {
      return arr
        .filter(item => item.dependsOn === parentId || (parentId === null && item.dependsOn === undefined))
        .map(item => ({
          ...item,
          children: buildTree(arr, item.id)
        }));
    }
    
    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 = buildTree(arr, null);
    console.log(treeTo);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search