We need to return the element from an array that passes a function. Both the function and the array are passed into our function findElement(arr, func).
Hints
Hint 1
We need to return the element from an array that passes a function. Both the function and the array are passed into our function findElement(arr, func). Looking through the array can be done with a for loop.
Hint 2
num is passed to the function. We will need to set it to the elements we want to check with the function.
Hint 3
Do not forget, if none of the numbers in the array pass the test, it should return undefined.
Solutions
Solution 1 (Click to Show/Hide)
function findElement(arr, func) {
let num = 0;
for (let i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
}
}
return undefined;
}
Code Explanation
Challenge asks us to look through array. This is done using a for loop.
The num variable is being passed into the function, so we set it to each index in our array.
The pre-defined function already checks each number for us, so if it is “true”, we return that num.
If none of the numbers in the array pass the function’s test, we return undefined.
Solution 2 (Click to Show/Hide)
function findElement(arr, func) {
return arr.find(func);
}
for (var i=0;i<arr.length;i++){ // loop through the provided array.
if (func(arr[i])) { // if the provided function is called & passed the parameter of the loops current element & returns true,
return arr[i]; // return the current loop element to the console.
}
}
return undefined; // if no element of the provided array passes the functions test return undefined.
}
function find`Eleme`nt(arr, func) {
//decalre an array to store all value that pass the test
var arr2 = [];
// add all values that pass the test on func
arr2 = ( arr.filter(function(el){
return func(el) ? arr2.push(el) : "";
}) );
//return first element that passed the test, if it didn't pass the test
//it will return undefined - exactly what we need!
return arr2[0];
}
//test
findElement([1, 3, 5, 9], function(num){ return num % 2 === 0; });