JS Built-ins
← Array111 / 226
ArrayArray.prototype.indexOfintermediate

Array.prototype.indexOf() β€” find first duplicate value

πŸ“– Usage Example
const arr = [3, 1, 4, 1, 5]
const first = arr.indexOf(1)   // β†’ 1
const second = arr.indexOf(1, first + 1)  // β†’ 3

Chain indexOf() calls with a fromIndex to locate successive duplicate values.

Array.prototype.indexOf() β€” detecting duplicates

By comparing indexOf(val) with lastIndexOf(val), you can tell whether a value appears more than once. The first value where they differ is the first duplicate.

Challenge: Implement firstDuplicate(arr) that returns the first value that appears more than once, or -1 if all values are unique.

firstDuplicate([1, 2, 3, 2, 1]) // β†’ 2 (first value that repeats)
firstDuplicate([1, 2, 3])        // β†’ -1
πŸ’‘ Hints (2)
  • β€’ A value is a duplicate when `arr.indexOf(val) !== arr.lastIndexOf(val)`.
  • β€’ Iterate and return on the first such value found.