How to Search an Array of Objects by Property in TypeScript?

In this tutorial, I will explain how to search an array of objects by property value in TypeScript. TypeScript provides several methods to search an array of objects. Using real-world examples, I will show you different techniques to find objects within an array based on specific property values.

The Problem: Finding Objects in an Array

Let’s say you’re working on a project that involves managing a list of employees in a US-based company. You have an array of employee objects, where each object contains properties like name, age, position, and state.

Your task is to find specific employees based on their properties, such as finding all employees from a particular state or with a certain position.

Here’s an example of what the employee array might look like:

const employees = [
  { name: "John Smith", age: 35, position: "Manager", state: "California" },
  { name: "Emily Johnson", age: 28, position: "Developer", state: "New York" },
  { name: "Michael Davis", age: 42, position: "Manager", state: "Texas" },
  { name: "Sarah Wilson", age: 31, position: "Designer", state: "California" }
];

Now, let me show you different methods to do so.

Check out Convert JSON to Array in TypeScript

Solution 1: Using the find() Method

One of the most straightforward ways to search an array of objects by property in TypeScript is using the find() method. The find() method returns the first element in the array that satisfies the provided testing function.

Here’s an example of how to use find() to search for an employee by name:

const employees = [
  { name: "John Smith", age: 35, position: "Manager", state: "California" },
  { name: "Emily Johnson", age: 28, position: "Developer", state: "New York" },
  { name: "Michael Davis", age: 42, position: "Manager", state: "Texas" },
  { name: "Sarah Wilson", age: 31, position: "Designer", state: "California" }
];
const employeeName = "Emily Johnson";
const employee = employees.find(emp => emp.name === employeeName);
console.log(employee);

In this code snippet, we use the find() method to iterate over the employees array and compare each employee’s name property with the desired employeeName. The find() method returns the first matching employee object.

I executed the above TypeScript code using VS Code and you can see the exact output in the screenshot below:

Search an Array of Objects by Property in TypeScript

Check out Remove Undefined Values from an Array in TypeScript

Solution 2: Using the filter() Method

If you need to find multiple objects that match a specific property value, you can use the filter() method. The filter() method creates a new array with all the elements that pass the test implemented by the provided function.

Let’s say you want to find all employees from the state of California. Here’s how you can achieve that using filter():

const employees = [
  { name: "John Smith", age: 35, position: "Manager", state: "California" },
  { name: "Emily Johnson", age: 28, position: "Developer", state: "New York" },
  { name: "Michael Davis", age: 42, position: "Manager", state: "Texas" },
  { name: "Sarah Wilson", age: 31, position: "Designer", state: "California" }
];
const californiaEmployees = employees.filter(emp => emp.state === "California");
console.log(californiaEmployees);

In this example, the filter() method iterates over the employees array and returns a new array containing only the employees whose state property matches “California”.

Here is the exact output in the screenshot below:

Unexpected EOF while parsing python

Read Sort an Array Alphabetically in TypeScript

Solution 3: Using a Custom Search Function

In some cases, you might need more flexibility in searching an array of objects. You can create a custom search function that takes the array, the property to search, and the value to match as parameters.

Here’s an example of a custom search function:

function searchByProperty<T>(array: T[], property: keyof T, value: any): T[] {
  return array.filter(obj => obj[property] === value);
}

This generic function takes an array array, a property property of type keyof T (which represents the valid property names of the object type T), and a value to match. It uses the filter() method internally to search for objects that have the specified property value.

You can use this custom search function as follows:

const employees = [
  { name: "John Smith", age: 35, position: "Manager", state: "California" },
  { name: "Emily Johnson", age: 28, position: "Developer", state: "New York" },
  { name: "Michael Davis", age: 42, position: "Manager", state: "Texas" },
  { name: "Sarah Wilson", age: 31, position: "Designer", state: "California" }
];
const managersFromTexas = searchByProperty(employees, "position", "Manager")
                            .filter(emp => emp.state === "Texas");
console.log(managersFromTexas);

In this example, we first use the searchByProperty() function to find all employees with the position of “Manager”. Then, we chain the filter() method to further narrow down the results to only managers from Texas.

Check out Remove Duplicates from an Array in TypeScript

Optimizing Search Performance

When working with large arrays of objects in TypeScript, searching can become a performance bottleneck. Here are a few tips to optimize search performance:

  1. Use appropriate methods: Choose the most suitable method for your search requirements. If you only need to find the first matching element, use find() instead of filter() to avoid unnecessary iterations.
  2. Create indexes: If you frequently search based on specific properties, consider creating indexes or maps to improve search efficiency. You can create a separate object or Map that maps property values to their corresponding objects, allowing for constant-time lookups.
  3. Lazy evaluation: If the array is large and you only need a subset of the search results, consider using lazy evaluation techniques like generator functions or pagination to load and process data in smaller chunks.

Conclusion

In this tutorial, I explained how to search an array of objects by property in TypeScript using different methods such as find(), filter(), or custom search functions. With the knowledge gained from this tutorial, you can efficiently search arrays of objects in your TypeScript projects, whether working on employee management systems, product catalogs, or any other domain requiring searching capabilities.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.