I'm attempting to recursively loop through an array in search of a key that matches a specified regex pattern. Once the condition is met, the loop should halt and return the value of the key.
The issue I am facing is that although the loop stops correctly when it finds a match, it only returns the value of the first key (index 0) in the array. For all subsequent keys, it returns 'undefined' instead.
Where did I go wrong? The following code demonstrates the problem:
function loop(arr, i) {
var i = i||0;
if (/i/gim.test(arr[i])) {
console.log("key value is now: " + arr[i]);
return arr[i]; // returning key value
}
console.log("key value: " + arr[i]); // test key value
i+=1; // update index
loop(arr, i); // call function with updated index
}
console.log(loop(["I", "am", "lost"]));
// Output:
// "key value is now: I"
// "I"
console.log(loop(["am", "I", "lost"]));
// Output:
// "key value: am"
// "key value is now: I"
// undefined