Skip to main content

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.

DEPRECATED

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)