Finders Keepers exercise

Hello everyone,

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.

  1. Although my code returns what is first element that pass the test, freeCodeCamp checker doesn’t agree. Why?
  2. 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; }));


generally, [] === [] returns false

This is due to how objects and arrays are compared. You should instead use item.length === 0

The function you’re implementing already exists btw, it’s Array.prototype.find but it’s good to reimplement it in some way I guess

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?

Thanks for answers guys.

I’ve tried with only .find() method and its cool - in one line code I passed the test. I’m still at beginning and i forgot about this one :slight_smile:

Still, when i write code like this,

function findElement(arr, func) {
 let item = arr.filter(func).slice(0,1); 
 if (item.length === 0){   
   return undefined;
 }
 return item;
}
console.log(findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }))

code returns 8, but in console I get message:
// running tests
findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }) should return 8.
// tests completed

…and cant pass the test.

Slice returns an array, so you simply need to get the first element of it :slight_smile:

1 Like

haha yes, returns array with one element,
and i wanted just the element

thanks