JS Built-ins
← Array72 / 226
ArrayArray.prototype.findIndexbeginner

Array.prototype.findIndex() β€” index of first match

πŸ“– Usage Example
const nums = [5, 12, 8, 130]
nums.findIndex(n => n > 10)  // β†’ 1  (index of 12)

Use findIndex() to get the index of the first element that satisfies a condition.

Array.prototype.findIndex()

Array.prototype.findIndex(callback) returns the index of the first element for which the callback returns truthy, or -1 if no match is found. It is the index-returning counterpart of find().

Challenge: Implement firstEvenIndex(nums) that returns the index of the first even number.

firstEvenIndex([1, 3, 4, 6]) // β†’ 2
firstEvenIndex([1, 3, 5])    // β†’ -1
πŸ’‘ Hints (2)
  • β€’ `findIndex()` returns the index, while `find()` returns the element.
  • β€’ Returns `-1` when no element satisfies the predicate.