Finders Keepers using .filter

Please help!!! It’s running but not passing the test:

Your code so far


function findElement(arr, func) {
  let num = 0;
  let ans = arr.filter(func).slice(0, 1);
  console.log(ans)
  return num;
}

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

Your browser information:

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

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

I’ve tried several things, still the same. How does one return an else after using filter?

I was changing the variables. Let me try using a for-loop…

How about assigning just the result of the filter to ans and then create an if statement which checks if ans is empty? If so, return undefined, otherwise return the first element of the filtered array. Also, instead of using slice(0,1), think about the easiest way to reference the first element of any array.

2 Likes

Wow, worked like magic!. I see what i was doing wrong. Thank you very much.