Why arr.indexOf( ) is not working?

Hey guys, I can’t figure out why my code is not working, even though it seems logical to me ?
Could anyone please tell me why?

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


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

Finders Keepers

Can you explain how you think your code works?

The callback returns true or false, its return value is what you are passing as an argument to indexOf.

console.log(1 % 2 === 0); // false
console.log(2 % 2 === 0); // true

indexOf looks through an array for an element with the same value as the argument passed to it. It will return the index of the element or -1 if it doesn’t find it.

Have you looked at the console? Console.log the last line.

indexOf expects a value to search for. What you are passing is conditional. Plus, what if you are given an array that is not sequential #'s starting at 1?

you are hard on me, I am learning guys :sweat_smile:

Ok I will dive into it, some basics I still haven’t mastered.

Thank you.

indexOf would have to be looping an array of true/false values which it isn’t.

If you really wanted that you can create an array of the values that the callback returns and then use indexOf on that array. You would then use the index indexOf returns to index into the array passed to the function. Not sure if that made any sense, it is kind of hard to explain.

This is pretty much what solution 3 on the hints page does. I do however find that approach hard to reason about, at least at first glance.

Thank you, yeah you’re right, it’s not the better way to solve it. I got to stop being stubborn with one method and try others next time.
Thanks :v: