JS Built-ins
← Array73 / 226
ArrayArray.prototype.findIndexintermediate

Array.prototype.findIndex() β€” find object index by id

πŸ“– Usage Example
const users = [{id:1}, {id:2}, {id:3}]
users.findIndex(u => u.id === 2)  // β†’ 1

Use findIndex() on an object array to find the position of a specific record.

Array.prototype.findIndex() β€” object arrays

findIndex() is often used with object arrays to get the index of an object with a specific property value.

Challenge: Implement indexOfId(items, id) that returns the index of the item with matching id.

indexOfId([{id:1},{id:2},{id:3}], 2) // β†’ 1
indexOfId([{id:1},{id:2}], 99)       // β†’ -1
πŸ’‘ Hints (2)
  • β€’ `findIndex` lets you search by any property, unlike `indexOf` which uses reference equality.
  • β€’ The returned index can be used to splice, update, or access the element.