How to Check if a TypeScript Array Contains a Specific Value (5 Methods)

When working with arrays in TypeScript, one of the most common operations is checking if an array contains a specific value. As someone who has worked with TypeScript for over six years, I’ve used this operation countless times in real-world applications.

Whether you’re validating user input, filtering data, or implementing search functionality, knowing how to check for element existence properly can make your code more efficient and readable.

In this tutorial, we will discuss several methods to check if a TypeScript array contains a specific value, along with practical examples that you can start using in your projects today.

Check if a TypeScript Array Contains a Specific Value (5 Methods)

Below, I will explain the five different methods to check if a TypeScript array contains a specific value.

Use includes() Method in TypeScript

The includes() method is the most straightforward way to check if an array contains a specific value in TypeScript.

const fruits: string[] = ['apple', 'banana', 'orange', 'kiwi'];

// Check if 'banana' exists in the array
const hasBanana: boolean = fruits.includes('banana'); // returns true

// Check if 'grape' exists in the array
const hasGrape: boolean = fruits.includes('grape'); // returns false

The includes() method is perfect for primitive values, such as strings and numbers. It’s also quite readable, making your code more maintainable.

Let’s look at a practical example where we check if a user’s favorite fruit is in our inventory:

function checkFruitAvailability(userFavorite: string): string {
  const availableFruits: string[] = ['apple', 'banana', 'orange', 'kiwi'];

  if (availableFruits.includes(userFavorite.toLowerCase())) {
    return `Good news! ${userFavorite} is available in our store.`;
  } else {
    return `Sorry, we don't have ${userFavorite} at the moment.`;
  }
}

// Usage
console.log(checkFruitAvailability('Banana')); // Good news! Banana is available in our store.
console.log(checkFruitAvailability('Mango')); // Sorry, we don't have Mango at the moment.

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

Check if a TypeScript Array Contains a Specific Value

Use the indexOf() Method in TypeScript

Another common way to check if an array contains a specific value is by using the indexOf() method. This method returns the index of the first occurrence of the element, or -1 if the element is not found.

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

// Check if 'Texas' exists in the array
const hasTexas: boolean = states.indexOf('Texas') !== -1; // returns true

// Check if 'Alaska' exists in the array
const hasAlaska: boolean = states.indexOf('Alaska') !== -1; // returns false

Here’s a practical example using indexOf() to check if a user’s state qualifies for free shipping:

function checkFreeShippingEligibility(userState: string): boolean {
  const freeShippingStates: string[] = ['California', 'Texas', 'Florida', 'New York'];

  return freeShippingStates.indexOf(userState) !== -1;
}

// Usage
const userState = 'Texas';
if (checkFreeShippingEligibility(userState)) {
  console.log(`Congratulations! You qualify for free shipping in ${userState}.`);
} else {
  console.log(`Free shipping is not available in ${userState} at this time.`);
}

Output:

Use indexOf method to check contains value in TypeScript array

Use the some() Method in TypeScript

The some() method is particularly useful when you need to check if an array contains a value that satisfies a specific condition. It’s especially powerful when working with arrays of objects.

const products = [
  { id: 1, name: 'Laptop', inStock: true },
  { id: 2, name: 'Phone', inStock: false },
  { id: 3, name: 'Tablet', inStock: true }
];

// Check if any product with name 'Phone' exists
const hasPhone = products.some(product => product.name === 'Phone'); // returns true

// Check if any product with name 'Headphones' exists
const hasHeadphones = products.some(product => product.name === 'Headphones'); // returns false

The some() method allows you to provide a custom comparison function as the callback, which is extremely useful for complex checks.

Here’s a practical example where we check if any product in the cart qualifies for express shipping:

interface Product {
  id: number;
  name: string;
  weight: number; // in pounds
}

function hasExpressShippingItem(cart: Product[]): boolean {
  // Items under 1 pound qualify for express shipping
  return cart.some(product => product.weight < 1);
}

// Example usage
const userCart: Product[] = [
  { id: 1, name: 'Heavy Book', weight: 2.5 },
  { id: 2, name: 'Phone Case', weight: 0.3 },
  { id: 3, name: 'Laptop', weight: 4.0 }
];

if (hasExpressShippingItem(userCart)) {
  console.log('Some items in your cart qualify for express shipping!');
} else {
  console.log('No items qualify for express shipping.');
}

Output:

Use the some() Method in TypeScript

Case-Insensitive Search in TypeScript

When working with user input, you might want to perform a case-insensitive search. Here’s how to do it with the methods we’ve discussed:

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

// Case-insensitive search using includes() and toLowerCase()
function containsCityIgnoreCase(cityName: string): boolean {
  return cities.some(city => city.toLowerCase() === cityName.toLowerCase());
}

console.log(containsCityIgnoreCase('chicago')); // true
console.log(containsCityIgnoreCase('HOUSTON')); // true
console.log(containsCityIgnoreCase('miami')); // false

Output:

Case-Insensitive Search in TypeScript

Checking for Substrings in Array Elements in TypeScript

Sometimes you need to check if any array element contains a specific substring. Here’s how to do it:

const descriptions: string[] = [
  'iPhone 13 Pro Max with 256GB storage',
  'Samsung Galaxy S21 with 128GB storage',
  'Google Pixel 6 with 64GB storage'
];

// Check if any description contains 'iPhone'
const hasIPhone = descriptions.some(desc => desc.includes('iPhone')); // true
console.log("Does any description contain 'iPhone'? ", hasIPhone);

// Check if any description contains '512GB'
const has512GB = descriptions.some(desc => desc.includes('512GB')); // false
console.log("Does any description contain '512GB'? ", has512GB);

This method is particularly useful for implementing search functionality, where you want to check if a string contains a substring.

Check for Substrings in Array Elements in TypeScript

Working with Object Arrays in TypeScript

When working with arrays of objects, you often need to check if an object with a specific property value exists. Here’s how to do it:

interface User {
  id: number;
  name: string;
  role: string;
}

const users: User[] = [
  { id: 1, name: 'John Doe', role: 'admin' },
  { id: 2, name: 'Jane Smith', role: 'user' },
  { id: 3, name: 'Bob Johnson', role: 'user' }
];

// Check if there's an admin user
const hasAdmin = users.some(user => user.role === 'admin'); // true

// Check if there's a user with id 4
const hasUser4 = users.some(user => user.id === 4); // false

// Check if there's a user named 'Jane Smith'
const hasJane = users.some(user => user.name === 'Jane Smith'); // true

Output:

Working with Object Arrays in TypeScript

Type Safety with Enums in TypeScript

TypeScript enums provide type safety when checking for specific values. Here’s how to check if an array contains a value from an enum:

enum UserRole {
  Admin = 'admin',
  User = 'user',
  Guest = 'guest'
}

const allowedRoles: UserRole[] = [UserRole.Admin, UserRole.User];

function hasAccess(role: UserRole): boolean {
  return allowedRoles.includes(role);
}

console.log(hasAccess(UserRole.Admin)); // true
console.log(hasAccess(UserRole.Guest)); // false

Checking if an enum contains a value is a common operation in TypeScript applications, especially when working with user permissions and access control.

Type Safety with Enums in TypeScript

Performance Considerations in TypeScript

When working with large arrays, performance becomes a concern. Here’s a quick comparison of the methods we’ve discussed:

  • includes(): Simple and readable, good for small to medium-sized arrays
  • indexOf(): Similar performance to includes(), slightly less readable
  • some(): More versatile but slightly slower for simple checks
  • find(): Similar to some() but returns the element instead of a boolean

For most web applications, the performance difference between these methods is negligible. Choose the one that makes your code most readable and maintainable.

When dealing with very large arrays (thousands of elements), consider using a Set data structure for O(1) lookup time:

const largeArray = ['value1', 'value2', /* thousands more values */];
const valueSet = new Set(largeArray);

// O(1) lookup time
const hasValue = valueSet.has('value1'); // true

Conclusion

I hope this article has given you a comprehensive understanding of how to check if an array contains a specific value in TypeScript. These methods can significantly enhance the readability and efficiency of your code when working with arrays.

Keep in mind that the best method depends on your specific use case. For simple checks with primitive values, includes() is usually the preferred approach. For more complex scenarios involving objects or custom conditions, some() provide the necessary flexibility.

You may like to read:

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.