1

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))
Joe M
  • 21
  • 3
  • You seem to be missing a fair bit. findLastIndex() works on array so you don't need to call it in a for loop - just return i in the loop or replace the whole loop with findLastIndex(). If you don't find the value why not just return undefined instead of findLast (which you know will fail). – John3136 Jan 24 '23 at 03:07
  • if I replace the for loop with findLastIndex() how do I use an else to return undefined instead of it returning -1? – Joe M Jan 24 '23 at 03:36
  • `let result = array.findLastIndex(callback); if (result === -1) { result = undefined; } return result;` – John3136 Jan 24 '23 at 03:58
  • Thank you John! Your answer changed how I think about what is possible with my code. Much appreciated. – Joe M Jan 24 '23 at 04:05

0 Answers0