JS Built-ins
← Array125 / 226
ArrayArray.prototype.lastIndexOfintermediate

Array.prototype.lastIndexOf() β€” detect duplicate values

πŸ“– Usage Example
const arr = [4, 2, 4, 2, 4]
arr.indexOf(4)      // β†’ 0  (first)
arr.lastIndexOf(4)  // β†’ 4  (last)

Use lastIndexOf() instead of indexOf() when you need the position of the last occurrence.

lastIndexOf() vs indexOf()

If indexOf and lastIndexOf return different indices for the same value, the value appears more than once in the array. This is a neat way to check for duplicates without iterating manually.

Challenge: Implement hasMultiple(arr, val) that returns true when val appears more than once.

hasMultiple([1, 2, 3, 2], 2) // β†’ true
hasMultiple([1, 2, 3], 2)    // β†’ false
πŸ’‘ Hints (3)
  • β€’ `indexOf` returns the **first** occurrence; `lastIndexOf` returns the **last**.
  • β€’ If they differ, the element must appear at least twice.
  • β€’ If the value is not present, both return `-1`, so they are equal β†’ returns `false`.