Search code examples
javascriptjavascript-objects

Creating a function to log all the hierarchies in the array order by the level


I am trying to create a function which logs all of the hierarchies in the array order by the level.

tried a lot of things but couldn't really figure out.

would like if you can help me out.

const arr = [
  { id: 1, parent_id: 8, level: 2, name: "person1" },
  { id: 2, parent_id: 1, level: 3, name: "person2" },
  { id: 8, parent_id: 0, level: 1, name: "person3" }
];

const func = (arr, level) => {

}

so the hierarchy by giving level 3 will be person2 => person1(since parent_id is 1) => person3(since parent_id is 8)

Thanks for helping !


Solution

  • One way is to change the function so you can call it recursively, then we can call 'ourself' until there are no parents found:

    const arr = [
      { id: 1, parent_id: 8, level: 2, name: "person1" },
      { id: 2, parent_id: 1, level: 3, name: "person2" },
      { id: 8, parent_id: 0, level: 1, name: "person3" }
    ];
    
    const getMatch = (arr, level, isParent = false) => {
      const key = (isParent) ? 'id' : 'level';
      const match = arr.filter(a => a[key] === level)[0];
      if (!match) { return false; }
      
      const parent = getMatch(arr, match.parent_id, true);
      return (parent) ? { ...match, parent } : match; 
    }
    
    const res = getMatch(arr, 3);
    console.log(res);

    {
      "id": 2,
      "parent_id": 1,
      "level": 3,
      "name": "person2",
      "parent": {
        "id": 1,
        "parent_id": 8,
        "level": 2,
        "name": "person1",
        "parent": {
          "id": 8,
          "parent_id": 0,
          "level": 1,
          "name": "person3"
        }
      }
    }