Finders Keepers help refactoring

I feel like I’m cheating here:

function findElement(arr, func) {

let num = 0;

num = arr.filter((num) => num % 2 === 0);

return num[0];

}

findElement([1, 3, 5, 8, 9, 10], num => num % 2 === 0);

Maybe I’m missing something but while this passes, I’m uncertain as to how to use “func” here, the second parameter of the functio, instead of hardcoding it in the body of the function?

Any help will be appreciated.

You’re assuming that the function will always be a check that the number is divisible by 2. It should be possible to call findElement with any function which returns a boolean.

If I were to call findElement([1, 3, 5, 9], function(num) { return num % 3 === 0; }) then I would want numbers divisble by 3. If I called findElement([1, 'three', 5, 9], function(thing) { return typeof thing === 'string'}) I would want only string elements.

Totally, I want to replace my hardcoded function with the actual parameter so any function can be passed in, problem is, I’m clueless as to how to do so in this scenario? My problem is how to use “func” in the body of my function.

Call the function, writing func() where you need it. Treat it as a function called func

1 Like

func is just a variable name assigned to the function you receive as an argument. It’s the name you can use to call that function.

1 Like

I see how to do this with a for loop the way you both say, calling the function. I really can’t figure out the syntax with the filter. Is it even doable…?

Edit I got it :stuck_out_tongue: Thx for the help.