Open In App

TypeScript Array find() method with Examples

Last Updated : 15 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The find() method in TypeScript searches the first element in the array, that satisfies the conditions of the testing function. If no element in the array satisfies the condition, the method returns undefined.

Syntax:

array.find(
callbackFn: (element: T, index?: number, array?: T[]) => boolean,
thisArg?: any
): T | undefined;

Parameters:

  • callbackFn: This is the heart of the find() method. It’s a function that gets called for each element in the array. You define the specific condition you’re searching for within this function.
  • thisArg (optional): This parameter allows you to specify a custom value to be used in this context when invoking the callbackFn.

Return Value:

  • The find() method returns the first element in the array that makes the callbackFn return true. Its type is the same as the array type (T). If no element satisfies the condition it will return undefined.

Examples of find() Method in TypeScript

Below are some of the examples of the TypeScript find() method. We can use the find function on both integers and strings.

Example 1: The below code implements the find() method to find the even elements contained by the array in TypeScript.

Javascript
const marks: number[] = 
[99, 94, 95, 98, 92];

const firstEvenMark: number | undefined = 
marks.find((mark) => {
    // Check if the current mark is even
    return mark % 2 === 0;
});

console.log(firstEvenMark);

Output:

94

Example 2: The below code finds a company with a workforce greater than 30 in the array. We have used the TypeScript array find by id method here.

Javascript
interface Company {
  name: string;
  desc: string;
  workForce: number;
}

const companies: Company[] = [
  { name: "GeeksforGeeks", desc: "A Computer Science Portal.", workForce: 200 },
  { name: "Company 2", desc: "Description 1", workForce: 30 },
  { name: "Company 3", desc: "Description 2", workForce: 10 },
];

const matchedCompany = companies.find(company => company.workForce > 30);

console.log(matchedCompany);

Output:

{
"name": "GeeksforGeeks",
"desc": "A Computer Science Portal.",
"workForce": 200
}

Unleash the full potential of JavaScript with TypeScript. Our beginner-friendly TypeScript tutorial guides you through the basics and prepares you for advanced development.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads