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; });

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

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; });