Hi guys , I am currently at the Basic Algorithm Scripting: Finders Keepers. which tells me to Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument). If no element passes the test, return undefined.
My question is how to get this or why is not working the while loop the same way the loop does. any suggestion would be greatly appreciated.
I did this:
function findElement(arr, func) {
let num = 0;
for(var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
}
}
return undefined;
}
console.log(findElement([8, 4, 3, 4], num => num % 2 === 0));
// here the output is = 8, which is fine since the condition was met in the first number of the array which causes the loop to end and return the desired value.
So, everything works good with the for loop condition, my real problem or I guess question is how to get the same result using the while loop.
function findElement(arr, func) {
let num = 0;
while (num < arr.length ){
num++;
num = arr[num];
if(func(num)){
return num;
}
}
return undefined;
}
console.log(findElement([8, 4, 3, 4], num => num % 2 === 0));
// this is the output = 4 .