Finders Keepers - why doesn't my code work?

I know the solution has a more concise code but I don’t understand why the code I wrote doesn’t work? What am I missing?

Also - I don’t understand why the solution doesn’t return all values in the array that pass the truth test (as it is using a for loop). The challenge asks for just the first one.

solution I refer to is here: (https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers/)

Your code so far


function findElement(arr, func) {

let trueArr = [];

for(let i = 0; i < arr.length; i++){
  if(func(arr[i] = true)){
    trueArr.push(arr[i]);
    return trueArr[0];
  } else {return undefined;}
}

}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers

Thanks for that.

I’ve amended the code to correct the function and change location of return function.

I don’t understand why it’s still not working. What am I missing?

function findElement(arr, func) {
let trueArr = [];

for(let i = 0; i < arr.length; i++){
  if(func(arr[i]) == 1){
    trueArr.push(arr[i]);
    
  } 
  
  else {return undefined;}
}


return trueArr[0];
}

remember that when you have an else statement at the end, one of the statements in the chain will always execute - you have a return statement inside the loop and a return statement will break from the function returning a value, you have a return undefined that will run as soon as the if condition is false

remember that func(arr[i]) returns a boolean, so you may want to compare it with true or false not with a number