How to Find an Object in an Array by Property in TypeScript?

When working with arrays in TypeScript, you often need to find an object based on a specific property value. In this tutorial, I will explain how to find an object in an array by property in TypeScript.

Find an Object in an Array by Property in TypeScript

Now, let me show you different methods to find an object in a array by property in TypeScript.

Using the find Method

The most straightforward way to find an object in an array by property is to use the find method. This method returns the first element in the array that satisfies the provided testing function. If no elements satisfy the testing function, it returns undefined.

Example

Imagine you are developing a web application for a library in New York City. You have an array of book objects, and you need to find a book by its ISBN.

interface Book {
    isbn: string;
    title: string;
    author: string;
    year: number;
}

const books: Book[] = [
    { isbn: "978-3-16-148410-0", title: "The Great Gatsby", author: "F. Scott Fitzgerald", year: 1925 },
    { isbn: "978-0-14-118263-6", title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960 },
    { isbn: "978-0-452-28423-4", title: "1984", author: "George Orwell", year: 1949 }
];

const isbnToFind = "978-0-14-118263-6";
const book = books.find(b => b.isbn === isbnToFind);

if (book) {
    console.log(`Found the book: ${book.title} by ${book.author}`);
} else {
    console.log("Book not found");
}

In this example, we use the find method to search for a book by its ISBN. The find method iterates through the books array and returns the first book object that matches the given ISBN.

Here is the exact output in the screenshot below:

Find an Object in an Array by Property in TypeScript

Read How to Find an Object in a TypeScript Array?

Handle Complex Scenarios

In real-world applications, you might need to handle more complex scenarios, such as searching for objects based on multiple properties or dealing with nested arrays.

Example: Finding a User by Multiple Properties

Consider a scenario where you have an array of user objects, and you need to find a user by their first and last name. This could be useful in a CRM system for a company based in San Francisco.

interface User {
    id: number;
    firstName: string;
    lastName: string;
    email: string;
}

const users: User[] = [
    { id: 1, firstName: "John", lastName: "Doe", email: "john.doe@example.com" },
    { id: 2, firstName: "Jane", lastName: "Smith", email: "jane.smith@example.com" },
    { id: 3, firstName: "Emily", lastName: "Johnson", email: "emily.johnson@example.com" }
];

const firstNameToFind = "Jane";
const lastNameToFind = "Smith";
const user = users.find(u => u.firstName === firstNameToFind && u.lastName === lastNameToFind);

if (user) {
    console.log(`Found the user: ${user.firstName} ${user.lastName} with email ${user.email}`);
} else {
    console.log("User not found");
}

Here, the find method is used with a more complex condition that checks both the firstName and lastName properties.

Read Calculate the Sum of an Array in TypeScript

Using TypeScript Generics for Reusability

To make your code more reusable and type-safe, you can use TypeScript generics. Generics allow you to create functions that work with any data type.

Example: Generic Find Function

Let’s create a generic function to find an object in an array by a specific property value. This function can be used with any array of objects, making it highly reusable.

function findByProperty<T, K extends keyof T>(arr: T[], key: K, value: T[K]): T | undefined {
    return arr.find(item => item[key] === value);
}

// Example usage with books array
const foundBook = findByProperty(books, "isbn", "978-0-14-118263-6");
if (foundBook) {
    console.log(`Found the book: ${foundBook.title} by ${foundBook.author}`);
} else {
    console.log("Book not found");
}

// Example usage with users array
const foundUser = findByProperty(users, "email", "jane.smith@example.com");
if (foundUser) {
    console.log(`Found the user: ${foundUser.firstName} ${foundUser.lastName}`);
} else {
    console.log("User not found");
}

In this example, the findByProperty function is a generic function that takes an array of objects, a key, and a value. It returns the first object that matches the given key-value pair.

Check out Reverse an Array in TypeScript

Performance Considerations

When working with large datasets, performance becomes a critical factor. The find method is efficient for small to moderately sized arrays, but for very large arrays, you might need to consider more advanced data structures or algorithms to improve performance.

Example: Using a Map for Faster Lookups

If you have a large dataset and need to perform frequent lookups, using a Map can significantly improve performance. A Map allows for constant-time complexity (O(1)) for lookups, compared to linear-time complexity (O(n)) for the find method.

const bookMap = new Map<string, Book>();
books.forEach(book => bookMap.set(book.isbn, book));

const fastBook = bookMap.get("978-0-14-118263-6");
if (fastBook) {
    console.log(`Found the book: ${fastBook.title} by ${fastBook.author}`);
} else {
    console.log("Book not found");
}

In this example, we create a Map from the books array, where the key is the ISBN and the value is the book object. This allows for much faster lookups compared to using the find method.

Conclusion

In this tutorial, I have explained how to find an object in an array by property in TypeScript using different methods, such as the find() method.

You may also like: