How to Check if a TypeScript Array Contains a Specific Value?

Recently, one of my team members asked about checking if an array contains a specific value in TypeScript. In this tutorial, I will explain how to determine whether a TypeScript array contains a specific value. TypeScript provides several methods to accomplish this. I will show you different methods, including the includes() method, indexOf() method, and using a loop to search for a value.

Using the includes() Method

The best way to check if a TypeScript array contains a specific value is by using the built-in includes() method. This method returns true if the array includes the specified element and false otherwise. Here’s an example:

const usaStates: string[] = ['California', 'Texas', 'Florida', 'New York'];

console.log(usaStates.includes('Texas')); // Output: true
console.log(usaStates.includes('Alaska')); // Output: false

In this example, we have an array called usaStates that contains the names of some states in the USA. By calling the includes() method on the array and passing the value we want to check (‘Texas’ and ‘Alaska’), we can easily determine if the array contains those values. The includes() method is case-sensitive, so make sure to match the case of the elements in the array.

Here is the exact output in the screenshot below:

Check if a TypeScript Array Contains a Specific Value

The includes() method has good browser support and is the recommended approach for checking if an array contains a specific value in TypeScript.

Check out Append Elements to an Array in TypeScript

Using the indexOf() Method

Another way to check if a TypeScript array contains a specific value is by using the indexOf() method. This method returns the index of the first occurrence of the specified element in the array, or -1 if the element is not found. Here’s an example:

const usCities: string[] = ['New York City', 'Los Angeles', 'Chicago', 'Houston'];

console.log(usCities.indexOf('Chicago') !== -1); // Output: true
console.log(usCities.indexOf('Boston') !== -1); // Output: false

In this example, we have an array called usCities that contains the names of some cities in the USA. By calling the indexOf() method on the array and passing the value we want to check (‘Chicago’ and ‘Boston’), we get the index of the first occurrence of that value in the array. If the value is not found, indexOf() returns -1. To determine if the array contains the value, we compare the returned index with -1 using the !== operator.

Here is the exact output in the screenshot below:

How to Check if a TypeScript Array Contains a Specific Value

While the indexOf() method works well, it is slightly less readable compared to the includes() method. However, it can be useful if you need to know the index of the element in the array.

Check out Initialize an Array in TypeScript

Using a Loop to Search for a Value

In addition to the includes() and indexOf() methods, you can also use a loop to manually search for a value in a TypeScript array. This approach gives you more control over the search process and allows you to perform additional operations if needed. Here’s an example:

const usaPresidents: string[] = ['George Washington', 'John Adams', 'Thomas Jefferson', 'James Madison'];

function containsPresident(arr: string[], president: string): boolean {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === president) {
      return true;
    }
  }
  return false;
}

console.log(containsPresident(usaPresidents, 'Thomas Jefferson')); // Output: true
console.log(containsPresident(usaPresidents, 'Abraham Lincoln')); // Output: false

In this example, we have an array called usaPresidents that contains the names of some USA presidents. We define a function called containsPresident that takes an array and a president’s name as parameters. Inside the function, we use a for loop to iterate over each element of the array. If the current element matches the given president’s name, we return true. If the loop completes without finding a match, we return false.

Using a loop to search for a value provides flexibility, but it may not be as concise as using the built-in includes() or indexOf() methods. However, it can be useful in scenarios where you need to perform additional operations or have more complex search criteria.

Check out Create and Use an Empty String Array in TypeScript

Case-Insensitive Search

By default, the includes() and indexOf() methods perform case-sensitive comparisons. If you want to perform a case-insensitive search, you can convert both the array elements and the search value to lowercase (or uppercase) before making the comparison. Here’s an example:

const usaCompanies: string[] = ['Apple', 'Microsoft', 'Amazon', 'Google'];

function containsCompanyCaseInsensitive(arr: string[], company: string): boolean {
  const lowerCaseArray = arr.map(item => item.toLowerCase());
  const lowerCaseCompany = company.toLowerCase();
  return lowerCaseArray.includes(lowerCaseCompany);
}

console.log(containsCompanyCaseInsensitive(usaCompanies, 'amazon')); // Output: true
console.log(containsCompanyCaseInsensitive(usaCompanies, 'Facebook')); // Output: false

In this example, we have an array called usaCompanies that contains the names of some well-known companies in the USA. We define a function called containsCompanyCaseInsensitive that takes an array and a company name as parameters.

Inside the function, we convert all the array elements to lowercase using the map() method and store them in a new array called lowerCaseArray. We also convert the company name to lowercase. Finally, we use the includes() method on the lowerCaseArray to check if it contains the lowercase company name.

By converting both the array elements and the search value to the same case, we can perform a case-insensitive search and find matches regardless of the original casing.

Check out How to Remove Empty Strings from an Array in TypeScript?

Check for Multiple Values in TypeScript Array

Sometimes, you may need to check if an array contains multiple values. You can use the includes() method in combination with the every() or some() method to achieve this. Here’s an example:

const usaStates: string[] = ['California', 'Texas', 'Florida', 'New York'];

const statesToCheck: string[] = ['Texas', 'New York'];

// Check if the array contains all the specified values
console.log(statesToCheck.every(state => usaStates.includes(state))); // Output: true

// Check if the array contains at least one of the specified values
console.log(statesToCheck.some(state => usaStates.includes(state))); // Output: true

In this example, we have the usaStates array and another array called statesToCheck that contains the states we want to search for. To check if the usaStates array contains all the states specified in statesToCheck, we use the every() method. It returns true if every element in statesToCheck is found in usaStates using the includes() method.

On the other hand, if you want to check if the usaStates array contains at least one of the states specified in statesToCheck, you can use the some() method. It returns true if at least one element in statesToCheck is found in usaStates using the includes() method.

Using every() and some() in combination with includes() allows you to perform more complex searches and checks on arrays.

Conclusion

In this tutorial, I explained different ways to check if a TypeScript array contains a specific value. We learned about the includes() method, which is the most straightforward and recommended approach. We also looked at the indexOf() method, which returns the index of the first occurrence of a value in the array. Additionally, we discussed using a loop to manually search for a value, providing more control over the search process.

We also covered how to perform case-insensitive searches by converting the array elements and search value to the same case. Lastly, we explored checking for multiple values using the includes() method in combination with every() or some().