Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive function does not iterate to next element in foreach

It seems to me that the code for the 2nd item in items is never reached in the for loop.

How to fix this method?

      class Item {
        items: Item[] =  [];
        constructor(public id: string){}
      }
    
function getItembyIdRecursively(id: string, items: Item[]) : Item  |undefined{

  for(const item of items)
  {
      if(item.id === id)
      {
          return item;
      }
      else
      {
          return getItembyIdRecursively(id,item.items);
      }
  }
  return undefined;
}
    
    
    const item1 = new Item("1");
    const item2 = new Item("2");
    item1.items.push(new Item("1.2"));
    const items = [item1, item2];
    
    const foundItem = getItembyIdRecursively("2", items);
    
    console.log(foundItem.id);

You can find a repro sample here:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sample repro link

>Solution :

The problem is your else statement, you are returning the result in all cases, even if it is undefined. Basically since the first Item has children, you return the result of search in its children, and since the id is not matched, you get undefined.

for(const item of items)
    if(item.id === id)
    {
        return item;
    }
    else
    {
        const elem = getItembyIdRecursively(id,item.items);
        if (elem) {
          return elem;
        }
    }
    return undefined;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading