Skip to content

How to return grandchilds names for each person in array JS?

The function should return the name of grandchildrens for a given id and store the result in an array.The process should continue till the last level of granchild. If the given Id does not have any child return empty array. I have made the code below:

var people = new Array();
people.push({ name: "Deni", id: 1, parentId: 2 });
people.push({ name: "eldi", id: 2, parentId: null });
people.push({ name: "ari", id: 3, parentId: null });
people.push({ name: "adi", id: 4, parentId: 5 });
people.push({ name: "ona", id: 5, parentId: 6 });

function findGrandChildren(people, Id, isNotFirstCall) {
  debugger;
  for (var i = 0; i < people.length; i++) {
    ind = 0;
    if (people[i].parentId == Id) {
      if (people[i].id != people.id) {

        return findGrandChildren(people, people[i].id, true);
      }
      else {
        if (people[i].parentId != Id) {
          if (isNotFirstCall == undefined) {
            return people[i].name;
          }
          else {
            return null;
          }

        }
      }
    }
  }
  return "Id not found";
}
alert(findGrandChildren(people, 2));

Answer

I guess I understood what you need and to me looks like you are going on the right way but since JS allows you create dictionaries very easily and this is create tool for indexing your information… in your problem I would index the people array by their parentId. Also… by your description you have to add them to an array up to the last grandchildren…

So…

const people = [];
people.push({ name: "Deni", id: 1, parentId: 2 });
people.push({ name: "eldi", id: 2, parentId: null });
people.push({ name: "ari", id: 3, parentId: null });
people.push({ name: "adi", id: 4, parentId: 5 });
people.push({ name: "ona", id: 5, parentId: 6 });
people.push({ name: "geni", id: 6, parentId: 1 });
people.push({ name: "ledi", id: 7, parentId: 2 });

const indexBy = (arr, key) => {
  const index = {};
  arr.forEach(item => {
    const value = item[key];
    if (!value) return;
    if (!index[value]) index[value] = [];
    index[value].push(item);
  });
  
  return index;
}

const findGrandChildren = (people, id) => {
  const index = indexBy(people, 'parentId');
  const granchildren = index[id] || [];
  return [].concat(
    ...granchildren.map(grandchild => {
      return [grandchild.name, ...findGrandChildren(people, grandchild.id)]
    }),
  );
}
//console.log(indexBy(people, 'parentId'));
console.log(findGrandChildren(people, 2));