How come these two code have the same result?

This is from Finder keepers:
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) {
  return arr.find(func);
}
function findElement(arr, func) {
  return arr[arr.map(func).indexOf(true)];
}

first, func is a function that accepts a value and returns true or false based on that value

you have in the first case the find method, which accepts a callback and returns the index of the first item in the array that return true for the callback

the second function happens the same thing, only that instead of using a single method it goes like this:

  • map will return a new arrays of booleans, as each element of the starting array will become true or false passed through the callback
  • then indexOf returns the index of the array of the first element that passes the truth test, because it is searching for true in the array returned from the map method.
  • at the and you have inside teh brackets a number, which can be an array index, and that would be of the first element that pass the test, or -1, so arr[...] becomes or one of the elements of the array, or for arr[-1] it becomes undefined
1 Like

@ieahleen thoroughly appreciate it :smile: