Home > Blockchain >  Recursive searching returns undefined
Recursive searching returns undefined

Time:12-06

I was just practicing some native Javascript and came across this problem. I'm building a comments widget and trying to implement a 'reply' button. For this I have to iterate through some n number of nested comments to find the correct one and push the reply to it's 'responses' attribute. This is my code so far:

 const recursiveSearch = (object, target) => {
    if(object.id === target) return object;

    let result;
    if(object.responses.length > 0) {
     object.responses.forEach(response => {
          if(response.id === target) {
              result = response;
              console.log('match found')
              console.log(response)
              return response
          } 
          
          else if(response.responses.length > 0) recursiveSearch(response, target) 
      })   
    };

    console.log('result Is')
    console.log(result)

    return result

}

The logs show the expected behavior just fine but when looking at the end return statement is undefined. Any way to get around this?

CodePudding user response:

You should return from the recursive call and assign to the result variable again.

const recursiveSearch = (object, target) => {
  if (object.id === target) return object;

  let result;
  if (object.responses.length > 0) {
    object.responses.forEach(response => {
      if (response.id === target) {
        result = response;
        console.log('match found')
        console.log(response)
        return response
      }

      else if (response.responses.length > 0) {
        result = recursiveSearch(response, target) // <--------------------
      }
    })
  };

  console.log('result Is')
  console.log(result)

  return result
}

You can also use a find instead of forEach. This is more efficient.

const recursiveSearch = (object, target) => {
  if (object.id === target) return object;

  const result = object.responses.find(response => {
    if (response.id === target) {
      console.log('match found')
      console.log(response)
      return response
    }

    else if (response.responses.length > 0) {
      return recursiveSearch(response, target)
    }
  })

  console.log('result Is')
  console.log(result)

  return result
}

CodePudding user response:

You forgot to return in your else if, but notice, you're inside a forEach, so maybe change it to regular for or use something else

  • Related