Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function returns undefined regardless of enough return statements

I have read a few questions and answers on it already. It looks like my recursive function has got enough "return" statements, so... I do not know why it returns undefined... I have added extra log statement to show that the function itself finds the element, but does not return it...

let animals = [
  {
    name: "dogs",
    id: 1,
    children: [
      {
        name: "lessie",
        id: 2
      },
      {
        name: "bark-a-lot",
        id: 3
      }
    ]
  },
  {
    name: "cats",
    id: 4,
    children: [
      {
        name: "meows-a-lot",
        id: 5,
        children: [
          {
            name: "meows-a-lot-in-the-morning",
            id: 6
          }
        ]
      },
      {
        name: "whisk-ass",
        id: 7
      }
    ]
  }
];

function recurseFind(node, id) {
  if (Array.isArray(node)) {
    return node.forEach(el => {
      return recurseFind(el, id);
    });
  } else {
    if (node.id === id) {
      console.log("node matched", node.id, id, node);
      return node;
    } else if (node.children) {
      return node.children.forEach(child => {
        return recurseFind(child, id);
      });
    } else {
      return "not found";
    }
  }
}

const found = recurseFind(animals, 6);
console.log("found", found, "wtf");
like image 432
J Doe Avatar asked Feb 21 '26 14:02

J Doe


1 Answers

forEach returns undefined, so

return node.forEach(el => {
  return recurseFind(el, id);
});

will always return undefined, no matter what the recursive calls find.

I'd use a for loop instead, and if a match is found, return it:

let animals = [
  {
    name: "dogs",
    id: 1,
    children: [
      {
        name: "lessie",
        id: 2
      },
      {
        name: "bark-a-lot",
        id: 3
      }
    ]
  },
  {
    name: "cats",
    id: 4,
    children: [
      {
        name: "meows-a-lot",
        id: 5,
        children: [
          {
            name: "meows-a-lot-in-the-morning",
            id: 6
          }
        ]
      },
      {
        name: "whisk-ass",
        id: 7
      }
    ]
  }
];

function recurseFind(node, id) {
  if (Array.isArray(node)) {
    for (const el of node) {
      const result = recurseFind(el, id);
      if (result) return result;
    }
  } else {
    if (node.id === id) {
      return node;
    } else if (node.children) {
      for (const child of node.children) {
        const result = recurseFind(child, id);
        if (result) return result;
      }
    }
  }
}

const found = recurseFind(animals, 6) || 'not found';
console.log("found", found);
like image 95
CertainPerformance Avatar answered Feb 23 '26 02:02

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!