The find() method in TypeScript searches the first element in the array, testing the function. If no element in the array satisfies the condition, the method returns undefined.
- Stops execution once a match is found (efficient).
- Returns the matched element, not its index.
- Does not modify the original array.
Syntax:
array.find(callback(element[, index[, array]])[, thisArg])- callback: A function to execute on each value in the array.
- element: The current element being processed.
- index (optional): The index of the current element.
- array (optional): The array
find()was called upon.
- thisArg (optional): Object to use as
thiswhen executing the callback.
Now, let us understand with the help of the example:
const numbers = [10, 20, 30, 40, 50];
const found = numbers.find((num) => num > 25);
console.log(found); // Output: 30
Output
30
Using find() with Objects
This is where find() becomes especially useful.
interface User {
id: number;
name: string;
age: number;
}
const users: User[] = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 },
];
const result = users.find(user => user.name === 'Bob');
console.log(result); // Output: { id: 2, name: 'Bob', age: 30 }
find() vs filter()
| Feature | find() | filter() |
|---|---|---|
| Return Type | Single element or undefined | Array of all matched elements |
| Stops Early | Yes | No |
| Use Case | Find the first match | Find all matches |
Conclusion
The Array.find() method in TypeScript is a concise and efficient way to locate the first element in an array that satisfies a condition. It's especially handy when working with arrays of objects, making your code more readable and maintainable.