Home > Blockchain >  Javascript recursive function to get all children for given node
Javascript recursive function to get all children for given node

Time:12-20

I have written a recursive function to get get all children (and children of each child and so on). But I am not able to return correct value from the function. I see that function actually make the list of the data which I want but somehow I am not able to return it from the for loop.

let data = [
  {
    "nodeId": "root",
    "name": "ROOT",
    "parentNodeId": null
  },
  {
    "nodeId": "1",
    "name": "one",
    "parentNodeId": "root"
  },
  {
    "nodeId": "2",
    "name": "Two",
    "parentNodeId": "1"
  },
  {
    "nodeId": "31",
    "name": "three",
    "parentNodeId": "2"
  },
  {
    "nodeId": "32",
    "name": "three-2",
    "parentNodeId": "2"
  },
  {
    "nodeId": "33",
    "name": "three-3",
    "parentNodeId": "2"
  },
  {
    "nodeId": "41",
    "name": "four 2-1",
    "parentNodeId": "32"
  },
  {
    "nodeId": "51",
    "name": "five 2-1-1",
    "parentNodeId": "41"
  },
  {
    "nodeId": "61",
    "name": "six 2-1-1-1",
    "parentNodeId": "51"
  },
  {
    "nodeId": "62",
    "name": "six 2-1-1-2",
    "parentNodeId": "51"
  },
  {
    "nodeId": "71",
    "name": "seven 2-1-1-2-1",
    "parentNodeId": "62"
  },
  {
    "nodeId": "81",
    "name": "eight 2-1-1-2-1-1",
    "parentNodeId": "71"
  },
  {
    "nodeId": "91",
    "name": "nine 2-1-1-2-1-1-1",
    "parentNodeId": "81"
  },
  {
    "nodeId": "101",
    "name": "ten 2-1-1-2-1-1-1-1",
    "parentNodeId": "91"
  },
  {
    "nodeId": "111",
    "name": "eleven 2-1-1-1-1",
    "parentNodeId": "101"
  }
]


function test(entities, id, result = []) {
  const childrens = entities.filter(x => x.parentNodeId === id)

  if (childrens.length === 0) {
    console.log('inside1', result)
    return result
  }
  result = [...result, ...childrens]
  for (const ele of childrens) {
    test(entities, ele.nodeId, result)
  }
}

const out = test(data, '32')
console.log('out', out)

if I pass '32' in below function, I want to get 32 and all of its children. So it should exclude root, 1, 2, 31 and 33. everything from 32 and downwards should be returned from the recursive function.

CodePudding user response:

You need to update the result array within the for loop and return the updated array:

function test(entities, id, result = []) {
  const childrens = entities.filter(x => x.parentNodeId === id);

  if (childrens.length === 0) {
    return result;
  }
  result = [...result, ...childrens];
  for (const ele of childrens) {
    result = test(entities, ele.nodeId, result);
  }
  return result;
}

const out = test(data, '32');
console.log('out', out);
  • Related