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

Array.prototype.indexOf() β€” search from index

πŸ“– Usage Example
const arr = [1, 2, 3, 1, 2]
arr.indexOf(1)     // β†’ 0
arr.indexOf(1, 1)  // β†’ 3  (starts at index 1)

Pass a fromIndex to indexOf() to skip past the first occurrence and find later ones.

Array.prototype.indexOf() β€” fromIndex

The optional second argument fromIndex tells indexOf where to start searching. This lets you find subsequent occurrences after a known position.

Challenge: Implement indexOfFrom(arr, val, from) that uses arr.indexOf(val, from).

indexOfFrom([1, 2, 1, 2], 2, 2) // β†’ 3
indexOfFrom([1, 2, 1, 2], 1, 1) // β†’ 2
πŸ’‘ Hints (2)
  • β€’ `fromIndex` specifies where to start β€” elements before it are skipped.
  • β€’ To find all occurrences, loop calling `indexOf(val, lastIndex + 1)` until `-1` is returned.