Open In App

TypeScript Array find() method with Examples

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:

Return Value:

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.

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.

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.

Article Tags :