Find a matching object index
Locate a record by a condition while retaining its position for replacement or removal.
JavaScript · Function
Array.prototype.findIndex() returns the index of the first array element whose testing function returns a truthy value. It returns -1 when no element matches.
Call findIndex() with a testing function. JavaScript invokes that function for array elements in ascending index order and stops as soon as it returns a truthy value, returning that element’s index; when no element matches, the result is -1.
findIndex(callbackFn)
findIndex(callbackFn, thisArg)| Name | Type | Description |
|---|---|---|
callbackFn | Function | A function invoked for each element. It should return a truthy value for a match and a falsy value otherwise; it receives element, index, and array. |
thisArg | any | Optional value used as this when invoking callbackFn. |
The index of the first element that passes the test; otherwise, -1.
-1, so do not treat the returned number as a valid index without checking it.const inventory = [
{ id: "a1", stock: 0 },
{ id: "b2", stock: 4 },
{ id: "c3", stock: 9 },
];
const index = inventory.findIndex((item) => item.stock > 0);
console.log(index); // 1The callback tests each inventory item in order; the method returns the index of the first item with stock available.
Locate a record by a condition while retaining its position for replacement or removal.
Determine whether an ordered collection contains an item satisfying a predicate while preserving its numeric location.
Inspect array-like structures that expose length and integer-keyed properties.
Array.prototype.findIndex() return?It returns the index of the first array element whose test callback produces a truthy value. The search proceeds from the lowest index upward and stops immediately after the first match.
Follow-up: How does it differ from find()? find() returns the matching element itself, whereas findIndex() returns its numeric position.
The callback receives the current element, its index, and the array on which findIndex() was called. A truthy callback result indicates a match; a falsy result continues the search.
Follow-up: How can callback context be supplied? Pass a second argument as thisArg; it becomes the callback's this value when the callback is invoked.
If no callback invocation returns a truthy value, the method returns -1. This distinguishes “not found” from a valid zero-based index, including index 0.
Follow-up: Can it be used on array-like objects? Yes: the method is generic and only requires a length property plus integer-keyed properties.
Array.prototype.find()Array.prototype.indexOf()TypedArray.prototype.findIndex()