# I get stuck with Finders Keepers can any one help

my code

function findElement(arr, func) {
var num = 0;
for(var i = 0; i < arr.length; i++){
if(func(arr[i])){
num = arr[i];
return num;
} else{
return undefined;
}

}
return num;
}

findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });

Your solution currently only looks at the first element in the array (arr) and returns the element if the function (func) evaluates to true.

In the test case below:

findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })

your solution only looks at the ā1ā in the array and then returns undefined, because it evaluated to false (it was not even). Remember, as soon as the return statement is encountered the function is exited whether or not array was fully iterated.

So if the function (func) evaluates to false, what should happen?

So if the function(func) evaluates to false the iteration will stop, so how can i complete the iteration?

Wait until the iteration of the array is complete and then return undefined, because if it has not already returned an element in which the function evaluates to true, you know there is nothing to return.

Also, you do not need to set num = 0. It would be better to just declare it and return num at the end of the function (as your current solution is doing). If you declare a variable but not initialize it (assign it a value), it automatically has the value undefined.

1 Like

thanks so much:grinning:

*****Finders Keepers (Solution)******

function findElement(arr, func) {

return arr.find(func);

}

findElement([1, 2, 3, 4], num => num % 2 === 0);

4 Likes

This is my solution

function findElement(arr, func) {
let num;
for( let i = 0; i < arr.length; i++) {
if(func(arr[i])) {
num = arr[i];
break;
}
}
return num;
}

let num; => num is undefined
then in the loop, if state is true, break the loop and assigned num to arr[i]

1 Like

This is great. I always used to look at the best solutions after finishing exercises but now it looks like that option is gone or Iām not seeing it. Either way I knew there must be a more efficient way to do this, thanks for posting!

1 Like

function findElement(arr, func) {
var num = 0;
for(var i = 0; i < arr.length; i++){
if(func(arr[i])){ // use the condition as it should if(func(arr[i])===true)
num = arr[i];
return num;
} else{ //assume that (func(arr[i])===false so here the function will return undefiend and stop running
return undefined;
}

}
return num;
}

findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });