Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Check if a Value Exists in an Array in TypeScript

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you several reliable ways to test whether a value is present in an array using TypeScript. You'll learn the built-in array methods that work across all modern JavaScript runtimes, how to handle different data types (numbers, strings, objects), and how to avoid common pitfalls like reference equality issues. By the end, you'll be able to choose the right method for your specific use case.

What You'll Need

  • A TypeScript project or a file with TypeScript installed (or a modern JavaScript environment that supports ES2016+).
  • Basic familiarity with arrays and TypeScript syntax.

Step-by-Step

  1. Identify the type of values in your array. Are they primitives (string, number, boolean) or objects (including arrays, dates, or class instances)? This determines which method is appropriate. For primitives, includes() is simplest. For objects, you'll often need some() with a custom comparison.

  2. For primitive values, use the includes() method. This is the most straightforward approach. It returns true if the array contains the specified value, and false otherwise.

    const fruits: string[] = ['apple', 'banana', 'orange'];
    const hasBanana = fruits.includes('banana'); // true
    const hasGrape = fruits.includes('grape');   // false
    

    Note that includes() uses strict equality (===) for comparison, so it works with numbers, strings, booleans, null, and undefined.

  3. For numbers, be careful with floating-point precision. If you're checking for a decimal value that results from calculations, includes() might fail due to rounding errors. For example:

    const values = [0.1 + 0.2]; // actually stores 0.30000000000000004
    values.includes(0.3); // false
    

    In such cases, use some() with a tolerance check:

    const hasApprox = values.some(v => Math.abs(v - 0.3) < 1e-9); // true
    
  4. For objects, use some() with a property comparison. Since objects are compared by reference, includes() will only return true if you pass the exact same object instance. To check if an object with certain property values exists, use some():

    interface User { id: number; name: string; }
    const users: User[] = [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' }
    ];
    const hasBob = users.some(user => user.name === 'Bob'); // true
    const hasId3 = users.some(user => user.id === 3); // false
    
  5. If you need the index of the element, use findIndex() or indexOf(). For primitives, indexOf() returns the first index where the value is found, or -1 if not present. For objects, findIndex() lets you provide a predicate:

    const index = fruits.indexOf('banana'); // 1
    const userIndex = users.findIndex(user => user.id === 2); // 1
    

    Then check if the index is not -1.

  6. For more complex conditions, use some() with any predicate. This is the most flexible method. It tests whether at least one element satisfies the provided function. It works for any type and any condition (e.g., checking a range, a regex, or a combination of properties).

    const numbers = [1, 5, 10, 15];
    const hasLargeNumber = numbers.some(n => n > 12); // true
    const hasEven = numbers.some(n => n % 2 === 0); // true
    
  7. Consider using find() if you need the element itself. find() returns the first element that matches the predicate, or undefined if none. This is useful when you want to retrieve the matching object, not just a boolean.

    const foundUser = users.find(user => user.name === 'Bob');
    if (foundUser) {
      // do something with foundUser
    }
    
  8. For sets of unique values, consider using a Set for faster lookups. If you need to check membership frequently and the array is large, converting to a Set gives O(1) average lookup time instead of O(n).

    const fruitSet = new Set(fruits);
    const hasBananaFast = fruitSet.has('banana'); // true
    
  9. TypeScript-specific: ensure type safety. When using includes() with a union type array, TypeScript may complain if the value you're checking isn't assignable to the array's element type. You can use a type guard or cast if necessary, but it's better to design your types correctly.

    type Fruit = 'apple' | 'banana';
    const fruitsTyped: Fruit[] = ['apple', 'banana'];
    fruitsTyped.includes('apple'); // OK
    fruitsTyped.includes('grape'); // Error: Argument of type '"grape"' is not assignable to parameter of type 'Fruit'.
    
  10. Test your code. Write a few test cases to confirm the behavior, especially edge cases like empty arrays, arrays with null/undefined, and arrays with duplicate values.

Common Mistakes

  • Using includes() on objects expecting value equality. This is the most common error. includes() uses reference equality, so two separate objects with identical properties will not match.
  • Forgetting that indexOf() returns -1. Some developers mistakenly check if (index) instead of if (index !== -1), which fails when the element is at index 0.
  • Using some() without a return statement in the predicate. The callback must return a truthy value. If you use braces, remember to include return.
  • Assuming includes() works with NaN. Actually, includes() does handle NaN correctly (unlike indexOf()), but many developers don't realize this and write extra code.
  • Type errors when checking a value that isn't in the array's type. TypeScript will flag this, but some developers use as any to bypass it, which defeats type safety.

Tips

  • Prefer includes() for primitives—it's the most readable and concise.
  • Use some() when you need a custom comparison or when dealing with objects.
  • If you need to check multiple values, consider using a Set for efficiency.
  • Remember that includes() and indexOf() use strict equality, so type coercion doesn't happen. '5' and 5 are different.
  • For large arrays, some() short-circuits as soon as a match is found, which can save time.
  • Use TypeScript's type system to your advantage—define union types or interfaces to avoid invalid checks.

Troubleshooting

  • My check returns false even though the value is in the array. If you're using includes() with objects, that's the issue. Switch to some() with a property comparison. If you're using numbers, check for floating-point precision.
  • TypeScript error: “Argument of type 'X' is not assignable to parameter of type 'Y'. This happens when the value you're checking isn't of the same type as the array elements. Either widen the array type or use a type guard.
  • My callback in some() always returns false. Check that you're actually returning a boolean from the callback. If you use curly braces, you need an explicit return statement.
  • I need to check for NaN but indexOf() returns -1. Use includes() instead, which handles NaN correctly.
  • Performance is slow for large arrays. If you're doing many lookups, convert the array to a Set once and use has().

Frequently Asked Questions

Can I use includes() with an array of objects?

Yes, but it only checks for the exact same object reference. If you want to check for an object with specific property values, use some() instead.

What's the difference between includes() and indexOf()?

Both check for a value using strict equality. The main difference is that includes() returns a boolean, while indexOf() returns the index or -1. Also, includes() correctly detects NaN, while indexOf() does not.

How do I check if an array contains any element that matches a condition?

Use some() with a callback function that returns a boolean. For example, arr.some(x => x > 10) checks if any element is greater than 10.

Is includes() supported in all browsers?

It's supported in all modern browsers and Node.js since version 6. For older environments, you might need a polyfill or use indexOf().

Can I check if an array contains a substring of a string element?

Yes, use some() with includes() on the string: arr.some(str => str.includes('sub')).

How do I check if an array is empty?

Use arr.length === 0 or arr.length > 0 to check if it has elements. There's no built-in isEmpty() method.