It took me a while to understand what was required of the challenge. So the loop iterates through every element of arr, and checks to see if the test in func passes on any of the elements, and returns the element that passes? I set up the loop, the if statement is probably wrong, and I set num to equal the arr[i] instance that passes. Any help?
function findElement(arr, func) {
let num = 0;
for (let i=0;i<arr.length;i++) {
if (arr[i]==func(num)) {
num=arr[i]
}
return num
}
}
console.log(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/84.0.4147.135 Safari/537.36.
The job is to test whether running the function with that particular array element returns true. You’re putting num, a placeholder unrelated to the array, in the function, and then comparing that to the value of the array element.
The loop should try out all the array elements in the function, one after the other, testing each time whether the function call itself returns true.
A way to test if a function call returns true might be if (func(item) == true).
PS I think the num parameter of the tests is throwing you off. It’s not a great name, since it has nothing to do with the num in the starting function.
Yeah the num is kinda confusing me, I heard of other people complaining of it too on different posts. So this is what I have so far as per the advice:
function findElement(arr, func) {
let num = 0;
for (let i=0;i<arr.length;i++) {
if (func(arr[i])==true) {
num=arr[i]
}
return num
}
}
console.log(findElement([1, 2, 3, 4], num => num % 2 === 0));
It’s not passing the tests but I had originally thought it was func(num)==true lol
You’re very close! I bet if you read the instructions carefully, you’ll see why it’s not passing. Hint, there are two tests and they’re testing for different kinds of outcomes.
Moved the return statement, thank you so much! It passed.
function findElement(arr, func) {
let num = 0;
for (let i=0;i<arr.length;i++) {
if (func(arr[i])==true) {
num=arr[i]
return num
}
}
}
console.log(findElement([1, 2, 3, 4], num => num % 2 === 0));
Nice! that works because a function that doesn’t return a value returns undefined.
You could also set it up to say something like “return undefined” or start off with “num = undefined” and then return num either way (probably TMI).
Ahhh, so it basically did the } else { return undefined; thing for me. Because it’s either the value or nothing because it didn’t pass the condition which is supposed to return a value if true. I actually tried that in the beginning and it passed the undefined test but I was assuming it was wrong so I got rid of it. I should get a live Cactus shipped out to you for the help! lol, I appreciate it