Add to an Array in TypeScript Only If the Value Exists (With Examples)

Have you ever found yourself needing to add an item to an array in TypeScript, but only if that item already exists somewhere—perhaps in another array or a database?

TypeScript provides several methods for checking existence and adding elements conditionally. In this tutorial, I’ll walk you through easy, practical methods to add to an array only if the value exists in TypeScript with examples.

Here are the methods, and you can execute them using the VS Code editor.

Method 1: Using includes() to Check Existence Before Adding

The best way to check if a value exists in an array in TypeScript is to use the includes() method. Here’s how I do it:

const validStates = ['CA', 'NY', 'TX', 'FL', 'WA'];
let favoriteStates: string[] = [];

const stateToAdd = 'TX';

if (validStates.includes(stateToAdd)) {
  favoriteStates.push(stateToAdd);
}

console.log(favoriteStates); // Output: ['TX']

How it works:

  • includes() checks if stateToAdd exists in the validStates array.
  • If it does, we add it to favoriteStates using push().

Here is the exact output in the screenshot below:

Add to an Array in TypeScript Only If the Value Exists

Tip:
This is perfect for simple value checks, such as strings or numbers.

Check out Typescript sort array of objects by date descending

Method 2: Using indexOf() for Compatibility

While includes() is modern and easy to read, sometimes you might need to support older environments. In such cases, indexOf() is a solid choice. Here is a complete example.

const validZipCodes = [90210, 10001, 60601, 77001];
let selectedZips: number[] = [];

const zipToAdd = 90210;

if (validZipCodes.indexOf(zipToAdd) !== -1) {
  selectedZips.push(zipToAdd);
}

console.log(selectedZips); // Output: [90210]

How it works:

  • indexOf() returns the index of the value if it’s found, or -1 if it’s not.
  • We only add the value if the index is not -1.

Here is the exact output in the screenshot below:

TypeScript Add to an Array Only If the Value Exists

Read Typescript filter array of objects

Method 3: Using a Helper Function for Reusability

If you find yourself repeating this pattern often, it’s a good idea to wrap it in a helper function. Here’s how I usually do it:

function addIfExists<T>(source: T[], target: T[], value: T): void {
  if (source.includes(value)) {
    target.push(value);
  }
}

// Example usage:
const availableProducts = ['Laptop', 'Smartphone', 'Tablet'];
let cart: string[] = [];

addIfExists(availableProducts, cart, 'Smartphone');
console.log(cart); // Output: ['Smartphone']

Method 4: Avoiding Duplicates—Add Only If Not Already in Target

In real-world applications, you often want to avoid adding duplicates. Here’s how you can combine the existence check with a duplicate check:

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

const cityToAdd = 'Los Angeles';

if (usCities.includes(cityToAdd) && !visitedCities.includes(cityToAdd)) {
  visitedCities.push(cityToAdd);
}

console.log(visitedCities); // Output: ['Chicago', 'Los Angeles']

Read Typescript reverse array

Method 5: Using Set for Efficient Lookups

If you’re working with large arrays and performance matters (think: tens of thousands of customer IDs), converting your source array to a Set can speed up existence checks.

const validCustomerIds = new Set([101, 202, 303, 404]);
let activeCustomers: number[] = [];

const customerIdToAdd = 202;

if (validCustomerIds.has(customerIdToAdd)) {
  activeCustomers.push(customerIdToAdd);
}

console.log(activeCustomers); // Output: [202]

Why use a Set?

  • Lookup with has() is very fast, even for large datasets.

Check out Typescript merge two arrays of objects

Add to an Array in TypeScript Only If the Value Exists – Example

I will provide a real-world example here.

Suppose you’re building a web app where users can save their favorite US states. While adding the states to an array, it will check if the value exists in the array.

Below is the complete code:

const allStates = [
  'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA',
  // ... all 50 state codes
  'WI', 'WY'
];

let userFavoriteStates: string[] = [];

function addFavoriteState(state: string): void {
  if (allStates.includes(state) && !userFavoriteStates.includes(state)) {
    userFavoriteStates.push(state);
  }
}

// Try adding a valid and an invalid state
addFavoriteState('CA');
addFavoriteState('XX'); // Invalid, won't be added

console.log(userFavoriteStates); // Output: ['CA']

Best Practices

Here are some best practices to follow when doing this.

  • Case Sensitivity: Array checks are case-sensitive. 'ca' won’t match 'CA'. Normalize values if needed.
  • Object References: For arrays of objects, includes() and indexOf() check references, not values. Use find() or a custom comparison for objects.
interface Product { id: number; name: string; }
const products: Product[] = [{ id: 1, name: 'Laptop' }];
const productToAdd = { id: 1, name: 'Laptop' };

// This will NOT work as expected:
products.includes(productToAdd); // false

// Use find instead:
products.find(p => p.id === productToAdd.id); // returns the product object
  • Performance: Use Set for large arrays to get O(1) lookup time.

Conclusion

In this tutorial, I explained how to add elements to an array in TypeScript only if they exist in another array (or source). With modern TypeScript, this is both simple and efficient—whether you use includes(), indexOf(), or a Set for larger data. I hope you found this tutorial helpful! If you have any questions or want to share your own tips, feel free to leave a comment below.

You may also like the following tutorials:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App