0
votes

Hello guys I need help with high-order function called ’find’ that takes two arguments – an array and a function.It will loop through the array and call the function that was sent as argument once for every value in the array. If the argument-function returns ‘true’ at some point during the loop then the find function will return that value.

function f(n) {
  return n > 2
}

function find(array, predicate) {
  for (let i=0; i< array.length; i++) {    
    if (predicate(i) === false) {
        //do nothing
} 
return i 
    
}

console.log(find([1, 2, 3], f))
//this is supposed to log 3 as an answer

So far i get 0 as an answer and I cant seem to figure out how to make the loop stop when the boolean becomes True. And how to get a hold of that number and return it.

1
if (predicate(array[i])) return array[i]…? - deceze

1 Answers

1
votes

You need to check and return the item of the array and a reversed check.

function f(n) {
  return n > 2
}

function find(array, predicate) {
  for (let i = 0; i < array.length; i++) {
    if (predicate(array[i])) return array[i];
  }
}

console.log(find([1, 2, 3], f))
//this is supposed to log 3 as an answer