Finders Keepers - Using .forEach instead

I already know the original solution to this. It is:

function findElement(arr, func) {


  for (var i = 0 ; i< arr.length ; i++) {
      if (func(arr[i])) {
        return arr[i];
      }
  };


return undefined;

}

However, what I am trying to do is re-attempting the challenges using a .forEach method instead as a means to practise using .forEach

Can someone guide me with why the below use of .forEach is not passing the test? Thanks

Your code so far


function findElement(arr, func) {


  arr.forEach(function(element) {
    if (func(element)) {
      return element;
    }

})

return undefined;

}

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



Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36.

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

 return element;

This return statement is for the function inside your forEach. It is not a return statement for findElement.

1 Like

You’re close…

You need to use a return and you need to use filter.

The return brings the value out of the function findElement.
filter() returns an array, and it removes elements which do not meet your function’s conditions.

note: you could also use map, but the values that fail the condition would return undefined.

function findElement(arr, func) {
     return arr.filter((element) => {
          if (func(element)) {
               return element;
          }
     });

     return undefined;
}

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