Aller au contenu principal

find()

find<T>(array, predicate): T | undefined

Iterates over elements of collection, returning the first element predicate returns truthy for.

DEPRECATED

Use array.find(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: T | undefined

The matched element, or undefined if not found.


See Also


Since

2.0.0


Also known as

find (Lodash, es-toolkit, Remeda, Ramda) · findFirst (Effect) · ❌ (Radashi, Modern Dash, Antfu)


Example

const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 35 }
];

// ❌ Deprecated approach
const found = find(users, user => user.age > 28);
console.log(found); // { name: 'Jane', age: 30 }

// ✅ Recommended approach
const foundNative = users.find(user => user.age > 28);
console.log(foundNative); // { name: 'Jane', age: 30 }

How it works?

Returns the first element that passes the predicate. Deprecated: Use array.find() directly (ES2015).

Native Equivalent

// ❌ find(arr, predicate)
// ✅ arr.find(predicate)

Use Cases

Locate item by condition 📌

Find a specific object in an array based on a matching condition.

const users = [{ id: 1, role: "admin" }, { id: 2, role: "user" }];
users.find(user => user.role === "admin");
// => { id: 1, role: "admin" }

Get matching configuration

Find a configuration entry that matches specific criteria.

const configs = [{ env: "dev", url: "localhost" }, { env: "prod", url: "api.com" }];
configs.find(c => c.env === process.env.NODE_ENV);

Retrieve first valid option

Find the first item that meets validation criteria.

const methods = [{ type: "card", valid: false }, { type: "paypal", valid: true }];
methods.find(m => m.valid);
// => { type: "paypal", valid: true }