Javier
Javier

Reputation: 2095

How to do a recursively method in javascript

I'm trying to create a recursive method to find.

But I don't understand why it finds the element but returns undefined.

How can solve it, please?

Here is my code:

export const findDmaFromHierarchy = (hierarchy: [], value: string): any => {
  let founded = undefined;
  hierarchy.forEach((dma: any) => {
    if (dma.children) {
      findDmaFromHierarchy(dma.children, value);
    }
    if (String(dma.value) === String(value)) {
      console.log("founded: ", dma);
      founded = Object.assign({}, dma);
      return founded;
    }
  });
  return founded;
};

Upvotes: 0

Views: 49

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386610

You could take Array#some and return early on found.

Then I suggest to check if the value is found and assign the object and return with true. To move this check in front of the function omits unnecessary checks for children objects.

For children take a temporary variable and check it and assign and return if truthy.

export const findDmaFromHierarchy = (hierarchy: [], value: string): any => {
  let found = undefined;
  hierarchy.some((dma: any) => {
    if (String(dma.value) === String(value)) {
      console.log("founded: ", dma);
      found = Object.assign({}, dma);
      return true;
    }

    if (dma.children) {
      let temp = findDmaFromHierarchy(dma.children, value);
      if (temp) {
          found = temp;
          return tru;
      }
    }
  });
  return found;
};

Upvotes: 0

Barmar
Barmar

Reputation: 781058

You don't set founded when the recursive call finds the value.

export const findDmaFromHierarchy = (hierarchy: [], value: string): any => {
  let founded = undefined;
  hierarchy.forEach((dma: any) => {
    if (dma.children) {
      founded = findDmaFromHierarchy(dma.children, value);
      if (founded) {
        return founded;
      }
    }
    if (String(dma.value) === String(value)) {
      console.log("founded: ", dma);
      founded = Object.assign({}, dma);
      return founded;
    }
  });
  return founded;
};

Upvotes: 1

Related Questions