The correct return value is lost in the chain of recursive function calls. After the correct value is found, any additional search queries will return incorrect values ββfrom this point.
A couple of ways to handle this:
1. Cancel the search
When the correct value is found, immediately return it all the way up the recursive stack, no longer looking for any current arrays or nested arrays. In other words, cancel the rest of the search.
@Barmer is an example of this. A key part of his code is the use of for loops, not the each method to iterate over arrays, since it is much easier to break the for loop.
2. Store the value somewhere safe
When the correct value is found, keep it somewhere safe, allow the search to continue, and after the initial function call completes access to the value. The easiest way is to store the correct value in a global variable, although this is not good practice as it violates the encapsulation of the function.
@shyam answer is a cleaner solution: passing a reference to a global variable as a parameter to the function, setting the parameter to the correct value, and then accessing the global variable after completing the initial function call.
Choice between two
Under the conditions of the laity, the alleged logic of the function can be summarized as follows: when you find what you are looking for, stop and let me know that it is right away. The only reason for continuing the search would be the presence of several pieces of data. I assume that is not the case here.
Of the two approaches, # 2 is a quick-fix workaround that should work fine but will further confuse anyone who trying to understand the intended logic of the function. Why is the search continuing if it only looking for a single piece of data that already been found?
# 1 is a refactoring of the function so that it behaves more consistently with the intended logic, which would make the function easier to understand. The function stops searching when it finds what it needs.