How to Remove Undefined Values from an Array in TypeScript?

Recently, I worked with arrays in TypeScript that contained undefined elements. We wanted to remove these undefined values from the array. In this tutorial, I will explain how to remove undefined values from an array in TypeScript using different methods. We will ensure to filter out undefined values and ensure our arrays only contain valid elements.

The Problem: Undefined Values in Arrays

Let’s consider a real-world scenario. Imagine you’re building a web application for a company based in the USA. You have an array of employee names, but some of the entries are undefined due to missing data. Here’s an example:

const employees: (string | undefined)[] = [
  'John Doe',
  undefined,
  'Jane Smith',
  'Michael Johnson',
  undefined,
  'Emily Davis'
];

Undefined values in the array can cause issues when processing the data or displaying it to users. We aim to remove those undefined values and create a clean array containing only valid employee names.

Now, let me show you different methods to remove undefined values from an array in TypeScript.

Check out Sort an Array Alphabetically in TypeScript

Solution 1: Using the filter() Method

The best way to remove undefined values from an array in TypeScript is by using the filter() method. The filter() method creates a new array with all elements that pass the test implemented by the provided callback function.

Here’s how we can use filter() to remove undefined values:

const employees: (string | undefined)[] = [
  'John Doe',
  undefined,
  'Jane Smith',
  'Michael Johnson',
  undefined,
  'Emily Davis'
];
const filteredEmployees = employees.filter((employee) => employee !== undefined);
console.log(filteredEmployees);

In this example, we pass a callback function to filter() that checks if each element is not equal to undefined. The resulting filteredEmployees array will only contain the valid employee names.

Here is the exact output in the screenshot below:

Remove Undefined Values from an Array in TypeScript

The .filter() method can be used to remove elements of the same type, remove all of a certain type, and everything in between.

Check out Remove Duplicates from an Array in TypeScript

Solution 2: Using Type Guards

Another approach to remove undefined values from an array in TypeScript is by using type guards. Type guards allow us to narrow down the type of a variable within a conditional block.

Here’s an example of using a type guard to filter out undefined values:

const employees: (string | undefined)[] = [
  'John Doe',
  undefined,
  'Jane Smith',
  'Michael Johnson',
  undefined,
  'Emily Davis'
];
const filteredEmployees = employees.filter((employee): employee is string => {
  return typeof employee === 'string';
});
console.log(filteredEmployees);

In this case, we use a type guard function that asserts the type of employee as string within the callback function. The typeof operator is used to check if the type of employee is strictly equal to 'string'. This ensures that only string values are included in the resulting array.

The exact output is in the screenshot below after I executed the above TypeScript code using VS code.

TypeScript Remove Undefined Values from an Array

The solution is to pass a type-guard function that tells TypeScript that you’re filtering out the undefined part of the type.

Check out How to Split an Array in TypeScript?

Solution 3: Using the Boolean Constructor

A concise way to remove falsy values, including undefined, from an array is by using the Boolean constructor as the callback function for filter().

Here’s how it works:

const employees: (string | undefined)[] = [
  'John Doe',
  undefined,
  'Jane Smith',
  'Michael Johnson',
  undefined,
  'Emily Davis'
];
const filteredEmployees = employees.filter(Boolean);
console.log(filteredEmployees);

The Boolean constructor function evaluates each element in the array. It returns true for truthy values and false for falsy values (including undefined). By passing Boolean directly to filter(), we effectively remove all falsy values from the array.

To generally remove any falsy value, we would call data = data.filter(Boolean); Since the Boolean() constructor returns true on truthy values and false on falsy values.

Check out Get Distinct Values from an Array in TypeScript

Handle Undefined Values in Other Scenarios

Removing undefined values from arrays is a common task, but you might also encounter situations where you need to handle undefined values in objects. Here are a couple of strategies to deal with undefined values in objects:

  1. Using Object.entries() and filter():
    You can use the Object.entries() method to get an array of key-value pairs from an object and then use the filter() method to remove entries where the value is undefined. Here’s an example:
   const person = {
     name: 'John Doe',
     age: undefined,
     city: 'New York'
   };

   const filteredPerson = Object.fromEntries(
     Object.entries(person).filter(([_, value]) => value !== undefined)
   );

In this case, Object.entries() returns an array of key-value pairs, which we filter based on the value not being undefined. Finally, Object.fromEntries() is used to convert the filtered entries back into an object.

  1. Using a custom function:
    You can create a custom function to remove undefined values from an object recursively. Here’s an example:
   function removeUndefined(obj: any): any {
     return Object.entries(obj)
       .filter(([_, value]) => value !== undefined)
       .reduce((acc, [key, value]) => {
         acc[key] = typeof value === 'object' ? removeUndefined(value) : value;
         return acc;
       }, {});
   }

   const person = {
     name: 'Jane Smith',
     age: undefined,
     address: {
       street: 'Broadway',
       city: undefined
     }
   };

   const filteredPerson = removeUndefined(person);

This custom removeUndefined function recursively filters out undefined values from an object and its nested objects.

One way to remove undefined values from an object is to use the Object.entries() method to get an array of key-value pairs, and then use the filter() method.

Conclusion

As a TypeScript developer, you will get the requirement to remove undefined values from arrays in TypeScript. There are multiple ways to achieve it. Using the filter() method with an appropriate callback function is a straightforward approach. Type guards provide a way to narrow down the type of elements within the array during filtering. The Boolean constructor can be used as a concise way to remove all falsy values, including undefined.

When working with objects that contain undefined values, you can use techniques like Object.entries() and filter() or create custom recursive functions to handle nested objects.

In this tutorial, I explained how to remove undefined values from an array in TypeScript using various methods with examples.

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.