Array.prototype.indexOfintermediateconst arr = [3, 1, 4, 1, 5]
const first = arr.indexOf(1) // β 1
const second = arr.indexOf(1, first + 1) // β 3Chain indexOf() calls with a fromIndex to locate successive duplicate values.
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