Finding elements starting from the end of an array has gotten a lot easier with the introduction of the at
, findLast
, and findLastIndex
methods!
With at
you no longer need to remember to access the end of the array like array[array.length - 1]
trick. You can just call .at[-1]
to get the last element!
findLast
and findLastIndex
work the same as their find
and findIndex
counterparts. But, they work backwards from the end of the array. This is useful if you know what you're accessing is going to be closer to the end.
const arr = [1,2,3,4,5,6,7,8,9,10]
const item = arr.find(el => el >=9) // in the operation, it call the function 9 times before we got result
Since we know the item we want to find is on the right hand side of array, we can use findLast
or findLastIndex
const arr = [1,2,3,4,5,6,7,8,9,10]
const item = arr.findLast(el => el >=9) // only call the function 1 time
.at()
const arr = [1,2,3,4,5,6,7,8,9,10]
const first = arr.at(0) // 1
const last = arr.at(-1) // 10