Finders Keepers Array Challenge

Tell us what’s happening:
I’m trying to loop through the array and test each item in the array to see if it returns a truthy value if passed onto the function func. The test array [1, 3, 5, 8, 9, 10] is not returning the value 8 as expected. Anyone to help identify where I got it all wrong?

  **Your code so far**

function findElement(arr, func) {
arr.map(item =>{
  if (func(item)){
    return item;
  }
});

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/90.0.4430.93 Safari/537.36.

Challenge: Finders Keepers

Link to the challenge:

HI @Calvin022 !

Welcome to the forum!

I don’t think map is the way to go.
Remember that map will create a new array which is not what you want for this problem.

Here are two options to consider.

No.1:
Just use a for loop to check if it passes the truth test or return undefined.

No.2:
You can use this helpful array method instead

map() returns an array consists of the returned value of the callback function on each of the original array element <== Particularly have a look under the header “When not to use map()”.

The challenge can be solved with basic loop statements.

It might also help to see what your current code is doing.
I would suggest adding a console.log for this map method to see what is happening.

function findElement(arr, func) {

let newArr = arr.map(item =>{
  if (func(item)){
    return item;
  }
});

console.log(newArr) // [ undefined, 2, undefined, 4 ]

return undefined;
}

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

You can see in the console.log that creating this new array doesn’t help you with the challenge.

That is why @gaac510 and I advise you to look at a simpler approach.

Hope that makes sense!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.