findIndex()
findIndex<
T>(array,predicate):number
Returns the index of the first element predicate returns truthy for.
Similar to find, but returns the index instead of the element itself.
Use array.findIndex(predicate) directly instead.
Reason:
Native equivalent method now available
Type Parameters
T: T
The type of elements in the array.
Parameters
array: T[]
The array to search.
predicate: (value, index, array) => boolean
The function invoked per iteration.
Returns: number
The index of the found element, or -1 if not found.
See Also
Since
2.0.0
Also known as
findFirstIndex (Effect) · findIndex (Lodash, es-toolkit, Remeda, Ramda) · ❌ (Radashi, Modern Dash, Antfu)
Example
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 35 }
];
// ❌ Deprecated approach
const index = findIndex(users, user => user.age > 28);
console.log(index); // 1
// ✅ Recommended approach
const indexNative = users.findIndex(user => user.age > 28);
console.log(indexNative); // 1
How it works?
Returns the index of the first element that passes the predicate.
Deprecated: Use array.findIndex() directly (ES2015).
Native Equivalent
// ❌ findIndex(arr, predicate)
// ✅ arr.findIndex(predicate)
Use Cases
Locate position for update 📌
Find the index of an item to update it in place.
const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
users.findIndex(u => u.id === 2);
// => 1
Check if item exists
Determine if an item exists by checking if index is >= 0.
const items = ["apple", "banana", "cherry"];
items.findIndex(i => i === "banana") >= 0;
// => true
Get insertion point
Find where to insert a new item in a sorted array.
const sorted = [10, 20, 30, 40];
sorted.findIndex(n => n > 25);
// => 2 (insert before 30)