How to return undefined instead of -1, findLastIndex()

65 Views Asked by At

In this challenge, I need to return the index position of the last element that is true for a callback. I know findLastIndex returns the last index position, however I need to return 'undefined' instead of -1 if the callback doesn't result in true. findLast() does this, so this was the only solution I could come up with. I believe there has to be a better way, my way feels silly. I have two arrays for testing.

 function findLastTrueElement(array, callback) {

    for(let i = 0; i < array.length; i++) {
  let cb = callback(array[i]) 
 if (cb === true) return array.findLastIndex(callback)
 
}
return array.findLast(callback)
}



 

 const nums = [11, 12, 13, 14, 15, 16, 17, 18, 19];
  //all odd array
 // const nums = [11, 17, 13, 19, 15, 9, 17, 7, 19];
 function isEven(n) {
 return (n % 2 === 0) 
 }
 console.log(findLastTrueElement(nums, isEven))
0

There are 0 best solutions below