Basic Algorithm Scripting - Finders Keepers

Tell us what’s happening:
Describe your issue in detail here.
Could someone explain why the first code doesn’t work in comparison to the second.
Your code so far
code 1

function findElement(arr, func) {
  let num = arr.slice();
  for(let i = 0; i < num.length; i++){
    if(func(num)){
      return num
    }
  }
  return undefined;
}

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

code 2:
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;
}
Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15

Challenge: Basic Algorithm Scripting - Finders Keepers

Link to the challenge:

Take a look what’s the num below let num = arr.slice();

console.log(num);

It should clear up, why func(num) might not give the expected result.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.