JS Built-ins
← Array122 / 226
ArrayArray.prototype.lastIndexOfbeginner

Array.prototype.lastIndexOf() β€” find last position

πŸ“– Usage Example
const arr = [1, 2, 3, 2, 1]
arr.lastIndexOf(2)  // β†’ 3  (last occurrence)

Use lastIndexOf() to find the index of the last occurrence of a value.

Array.prototype.lastIndexOf()

Array.prototype.lastIndexOf(searchElement, fromIndex?) searches the array from right to left and returns the index of the last occurrence of searchElement. If not found, it returns -1.

Challenge: Implement lastPos(arr, val) that returns the last index of val in arr.

lastPos([1, 2, 3, 2, 1], 2) // β†’ 3
lastPos([1, 2, 3], 3)       // β†’ 2
πŸ’‘ Hints (2)
  • β€’ `lastIndexOf` scans from the end of the array to the beginning.
  • β€’ When there are duplicates, it returns the index of the rightmost match.