I’m doing this exercise where I need 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.
I can do it with for loop but i wanted to do it with some methods.
So I have a 2 questions about my code bellow.
Although my code returns what is first element that pass the test, freeCodeCamp checker doesn’t agree. Why?
I intentionally put “console.log(item)” to see what will be returned when it doesn’t find item. Why i’m not getting “undefined” return ?
Thanks
Your code so far
function findElement(arr, func) {
let item = arr.filter(func);
console.log(item)
if (item ===[]){
return undefined;
}
return item.slice(0,1);
}
console.log(findElement([1, 2, 3, 4], num => num % 2 === 0));
console.log(findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }));
console.log(findElement([1, 3, 7, 9], function(num) { return num % 2 === 0; }));
You are returning undefined because [] === [] is false. You cannot compare the contents of two arrays using an equality operator. What else can you use to check for an empty array?