Create a function that looks through an array arr and returns the first element in it that passes a 'truth test'. This means that given an element x, the 'truth test' is passed if func(x) is true. If no element passes the test, return undefined.
function findElement(arr, func) {
let num = 0;
return num;
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
Notes:
If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd. You can check for this using num % 2 == 1 .
1 % 2 = 1 because its odd
2 % 2 = 0 because its even
4 % 2 = 0 because its even
*Answer:
function findElement(arr, func) {
for (let i = 0; i < arr.length; i++)
if (func(arr[i])) {
return arr[i];
}
return undefined;
}
console.log(findElement([1, 2, 3, 4], num => num % 2 === 0)); // will display 4
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)