Sveta Pershay
Sveta Pershay

Reputation: 61

Recursive search for descendants by parent ID

I have flat array (flatten tree). How to implement a recursive search for children by parentIds using Lodash library?

For example by id = 1 I need to get 'JavaScript', 'React' and 'Vue'.

array: 
  [{
    id: 1,
    name: 'Development',
    parentIds: [],
  },
  { 
    id: 2,
    name: 'JavaScript',
    parentIds: [1] 
  },
  { 
    id: 3,
    name: 'React',
    parentIds: [2]
   },
   {
     id: 4,
     name: "Vue",
     parentIds: [2]
   }]

Upvotes: 1

Views: 465

Answers (2)

Vikash_Singh
Vikash_Singh

Reputation: 1896

See the below solution, i have used lodash library and recursive function :

function foo(array, pid, res = [], did = []) {
  array = _.filter(array, (obj) => {
    if (_.includes(obj.parentIds, pid) || _.intersection(obj.parentIds, did).length) {
      res.push(obj.name);
      did.push(obj.id);
      return false;
    } else {
      return true;
    }
  });
  res = Array.from(new Set(res));
  did = Array.from(new Set(did));
  if (array.length >= did.length) {
    res.push(foo(array, pid, res, did));
  }
  return Array.from(new Set(res));
}

Upvotes: 0

BryanOConnor
BryanOConnor

Reputation: 11

    $(function () {
        var array =
      [{
        id: 1,
        name: 'Development',
        parentIds: [],
      },
      {
        id: 2,
        name: 'JavaScript',
        parentIds: [1]
      },
      {
        id: 3,
        name: 'React',
        parentIds: [2]
       },
       {
         id: 4,
         name: "Vue",
         parentIds: [2]
       }]

        var getId = function (arrayItems, id) {
            if (arrayItems) {
                for (var i in arrayItems) {
                    if (arrayItems[i].id == id) {
                        return arrayItems[i];
                    };
                    var found = getId(arrayItems[i].items, id);
                    if (found) return found;
                }
            }
        };

        var searchedItem = getId(array, 3);
        alert(searchedItem.name);
    });

Upvotes: 1

Related Questions