Why in this challenge 10%2 is not === 0?

hi!
So the console logs out only 2 and 8, but what about 4 and 10 ?
8%2 === 0
10% 2 also ===0, as any other even number;
Your code so far


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([1, 2, 3, 4], num => num % 2 === 0));
console.log(findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }))


  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36.

Challenge: Finders Keepers

Link to the challenge:

the first one for which num % 2 === 0 is true is returned, so the others are never tested

when a return statement is executed the function stops and gets an output

1 Like

Thank you! But how do I test and log out all the right answers then? It’s not required by the challenge, but I want to know , try and understand

you can’t with the current setup, you would need to not have a return statement in the loop to see all the elements that pass the test

if you do if(func(num)) {console.log(num)} you can see all fo them but the tests now fail

1 Like

Thank you so much , I would’ve sat thinking about this for ages.
<3

The thing you’re looking for is .filter():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Answering your question regarding how to see all the values that would match, would mean the challenge was written as follows:

Create a function that looks through an array arr and returns an array of all elements in it that pass a ‘truth test’. This means that given an element x , the ‘truth test’ is passed if func(x) is true . If no elements passes the test, return undefined .

Then, a possible solution would be:

function findElements(arr, func) {
  const matchingElems = [];
  for (let i = 0; i < arr.length; i++) {
    const elem =  arr[i];
    if (func(elem)) {
      matchingElems.push(elem);
    } 
  }
  if (matchingElems.length) {
    return matchingElems;
  }
  return undefined;
}

findElements([1, 2, 3, 4], num => num % 2 === 0); // [2, 4]

or a more condensed version as suggested by @chuckadams:

function findElements(arr, func) {
  const matchingElems = arr.filter(func);
  return matchingElems.length ? matchingElems : undefined;
}

console.log(findElements([1, 2, 3, 4], num => num % 2 === 0)); // [2, 4]
1 Like