Finders Keepers Challenge

Hey guys, I already figure out this solution below. I solved it through this way. I was able to print 2 which is the first even number. Also, I’m trying to print 4 as well since it’s an even number. Not sure why it’s just returning 2 only. What am I missing here?

function findElement(arr, func) {
  let num = 0;
  for ( let i = 0; i < arr.length; i++){
    if(func(arr[i]) === true){
      return arr[i];
    }
  }
  
}

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

A return statement terminates a function. The first time that your condition is true, the loop stops.

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I also added spoiler tags since you code is a solution.

Okay, it actually works once I remove the return statement and just console.log(arr[i]) it. Thanks. How would I be able to return 2 and 4 without it not terminating right at 2?

If you want to return multiple things, you need to have a way to store multiple things. What data structure do you know that stores multiple things?

I guess Arrays, I’m thinking?

Yep. I would need to put everything you want to return into an array and return that array.

1 Like

Oh okay, can I just declare a variable with an empty array, and then push arr[i] into it, and return it?

Hey Jeremy, it works!!! Thank you so much for the input!

1 Like

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