I think you should first look at your for loop, it looks like an infinite loop. As you are looping through the arr array, you can access each element of the array using the index with the first element of the array starting at index 0.
For example, using the arr = [1, 3, 5, 8, 9, 10], arr[0] returns 1, arr[1] returns 3, arr[2] returns 5, arr[3] returns 8, etc…
So now, you need to know how to use the func.
Example: findElement([1, 3, 5, 8, 9, 10], num => num % 2 === 0);
-
arr will be [1, 3, 5, 8, 9, 10]
-
func will be num => num % 2 === 0. This function takes in a num and will return a boolean value. It will return true if it’s divisble by 2 (since an even # divided by 2 gives 0 remainders), false otherwise.
So what you want to do is call func on each element of arr. This is where your for loop comes in.
- At index 0,
arr[0] is 1. func(arr[0]) evaluates if 1 % 2 === 0, which returns false. Since that returns false, go to the next index.
- At index 1,
arr[1] is 3. func(3) evaluates to false as well.
- At index 2,
arr[2] is 5. func(5) evaluates to false as well.
- At index 3,
arr[3] is 8. func(8) evaluates to true. Since it is true, you can set num = 8 and break the for loop.
You can return num as the answer. However, if you have an arr = [1, 3, 5, 9], nothing satisfies the num % 2 === 0 condition since they’re all odd numbers. Personally, I would have set num to undefined like so:
function findElement(arr, func) {
let num = undefined;
for (...) {
...
}
return num;
}
So if the for loop couldn’t find anything that satisfies the func call (that returns true), num will still stay as undefined and it will return undefined. It there is an element in the array that has func return true, num will be set to that element’s value.