I get stuck with Finders Keepers can any one help

I get stuck with Finders Keepers can any one help
0

#1

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

#2

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?


#3

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


#4

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.


#6

thanks so much:grinning:


#7
 *****Finders Keepers (Solution)******

function findElement(arr, func) {

return arr.find(func);

}

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


#8

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]


#9

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!


#10

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


#11