JS Built-ins
← Array76 / 226
ArrayArray.prototype.findIndexadvanced

Array.prototype.findIndex() β€” find by property vs reference

πŸ“– Usage Example
const arr = [1, 2, 3, 2]
arr.indexOf(2)               // β†’ 1  (exact match)
arr.findIndex(n => n >= 2)   // β†’ 1  (predicate match)

Use findIndex() over indexOf() when you need a condition, not just an equality check.

Array.prototype.findIndex() β€” property-based search

indexOf uses strict reference equality for objects. findIndex lets you search by a property value instead, which is more useful when working with object arrays.

Challenge: Implement indexOfObject(arr, target) that uses findIndex to find the first object whose id property matches target.id.

indexOfObject([{id:1,name:'A'},{id:2,name:'B'}], {id:2,name:'X'}) // β†’ 1
πŸ’‘ Hints (2)
  • β€’ `indexOf(target)` would never match because it checks reference equality β€” the target is a different object.
  • β€’ `findIndex(o => o.id === target.id)` compares a primitive value instead.