RogerMax
RogerMax

Reputation: 3

How to iterate through a list using recursion

I've got a list like this below and I'm trying to get a list of all subnodes. I need to find all children and subchildren of a list. In this case it should return exact this list.

const data = [
  {
    id: 1,
    parent: 0,
  },
  {
    id: 2,
    parent: 1,
  },
  {
    id: 3,
    parent: 1,
  },
  {
    id: 4,
    parent: 3,
  }
];

I'm trying to choose whether or not call the function again in many ways but the result is always wrong.

const getNodes = (n) => {
   
  let family = [];
  for (let i of n) {
    const sons = data.filter(x => x.parent === i.id); 
    if (sons.length !== 0) {
      family.push(getNodes(sons));
    } else {
      family.push(i);
    }
  }
  return family;
};

console.log(getNodes([data[0]]));

Upvotes: 0

Views: 43

Answers (1)

IT goldman
IT goldman

Reputation: 19493

Let's transform that to a tree.

const data = [{
    id: 1,
    parent: 0,
  },
  {
    id: 2,
    parent: 1,
  },
  {
    id: 3,
    parent: 1,
  },
  {
    id: 4,
    parent: 3,
  }
];

// first obj of nodes grouped by id
var obj_nodes = data.reduce(function(agg, item) {
  agg[item.id] = { ...item, children: [] };
  return agg;
}, {})
// console.log(obj_nodes)

// connecting edges (child parent relations)
data.forEach(function(item) {
  var source = obj_nodes[item.id];
  var destination = obj_nodes[item.parent];
  
  destination && destination.children.push(source);
}, {})

var trees = Object.values(obj_nodes);

var result = trees[0]
console.log(result)
.as-console-wrapper {max-height: 100% !important}

Upvotes: 1

Related Questions