Finders Keepers using .filter

Finders Keepers using .filter
0

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

Your function returns the value 0 no matter what you pass to the function.

You initialize num to 0 in the first line of the function and do not change num before returning it.

FYI - Once you fix this issue, you will still have another issue in that what if none of the elements in the array passed to the function result in the passed function returning true. This means that ans will contain an empty array when ans should be undefined.

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

What code are you trying now?

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.