Finders Keepers help?

Tell us what’s happening:
Hi. :slight_smile: I am doing the Finders Keepers challenge and the code does filter between odd and even numbers, but I’m not sure how to get it to return as undefined if it’s an odd number. I just get an empty array. Can anyone help?

Your code so far


function findElement(arr, func) {
/* let num = 0;
 return num;*/
  let newArr = [];
  for (let i = 0; i < arr.length; i++) {
  newArr = arr.filter(func);
  return newArr;
  }
}

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

/* How to return as undefined ? */

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 YaBrowser/18.9.1.954 Yowser/2.5 Safari/537.36.

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

You can simply return undefined by

  for (let i = 0; i < arr.length; i++) {
    if(arr[i] % 2 !== 0) {
      return undefined;
    }
  }
1 Like

You don’t need the for loop. Filter will return an array with the elements that pass the test. Of these you need to extract the first element. If the array is empty, return undefined.

1 Like

Thank you so much!! That helped steer me in the right direction.

This was the solution that I came up with:

function findElement(arr, func) {

  let newArr = [];
  let secondArr = [];

  newArr = arr.filter(func);
  secondArr = newArr.shift(0);
  
if (newArr.length > 0) {
  return secondArr;
    } else {
  return undefined;
  } 
}

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