How to Remove Items from Arrays in TypeScript (7 Powerful Methods)

Do you required to remove specific items from an array in TypeScript? It is easy and there are various methods available in TypeScript. In this tutorial, I’ll walk you through several different techniques to remove items from arrays in TypeScript, complete with practical examples you can apply to your own projects right away.

Whether you need to remove elements by index, value, or based on specific conditions, TypeScript offers multiple approaches. Let’s dive in and explore these methods one by one!

Method 1: Using the splice() Method

The splice() method in TypeScript is perhaps the most versatile way to remove items from an array in TypeScript. It modifies the original array and can remove elements from any position.

Here’s how to use it:

// Initialize an array
let fruits: string[] = ['apple', 'banana', 'orange', 'grape', 'kiwi'];

// Remove an item at index 2 (orange)
fruits.splice(2, 1);

console.log(fruits); // Output: ['apple', 'banana', 'grape', 'kiwi']

In the example above, the first parameter (2) specifies the starting index, and the second parameter (1) indicates how many elements to remove.

Here is the exact output in the screenshot below:

Remove Items from Arrays in TypeScript

You can also remove multiple elements at once:

let numbers: number[] = [1, 2, 3, 4, 5, 6, 7];

// Remove 3 elements starting from index 2
numbers.splice(2, 3);

console.log(numbers); // Output: [1, 2, 6, 7]

The splice() method is particularly useful because it preserves the array’s original type while modifying its contents.

Check out Add to an Array in TypeScript Only If the Value Exists

Method 2: Using the filter() Method

If you want to remove elements based on a condition without modifying the original array, the filter() method is your best option in TypeScript. It creates a new array with all elements that pass the test implemented by the provided function.

Here is an example.

// Array of products
let products: {id: number, name: string, price: number}[] = [
    {id: 1, name: 'Laptop', price: 999},
    {id: 2, name: 'Phone', price: 699},
    {id: 3, name: 'Tablet', price: 399},
    {id: 4, name: 'Watch', price: 199}
];

// Remove products priced over $500
let affordableProducts = products.filter(product => product.price <= 500);

console.log(affordableProducts);
// Output: [{id: 3, name: 'Tablet', price: 399}, {id: 4, name: 'Watch', price: 199}]

You can see the exact output in the screenshot below:

TypeScript Remove Items from Arrays

You can also use filter() to remove undefined values from an array:

let mixedData: (string | undefined)[] = ['apple', undefined, 'banana', undefined, 'orange'];

// Remove all undefined values
let cleanData = mixedData.filter((item): item is string => item !== undefined);

console.log(cleanData); // Output: ['apple', 'banana', 'orange']

The filter() method is a clean, functional approach that doesn’t alter your original data.

Read Push Objects into an Array in TypeScript

Method 3: Using slice() to Create a New Array

The TypeScript slice() method creates a shallow copy of a portion of an array into a new array without modifying the original array. While it doesn’t directly “remove” items, you can use it to create a new array that excludes certain elements.

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

// Create a new array without the 3rd element (Florida)
let newStates = [...states.slice(0, 2), ...states.slice(3)];

console.log(newStates); // Output: ['California', 'Texas', 'New York', 'Illinois']

This approach is useful when you want to preserve the original array and create a new one with the desired changes.

Method 4: Using pop() to Remove the Last Element

If you need to remove the last element from a TypeScript array, the pop() method is the simplest solution. It modifies the original array and returns the removed element.

let team: string[] = ['John', 'Sarah', 'Mike', 'Emily'];

// Remove the last team member
let removedMember = team.pop();

console.log(team); // Output: ['John', 'Sarah', 'Mike']
console.log(removedMember); // Output: 'Emily'

Check out Get Distinct Values from an Array in TypeScript

Method 5: Using shift() to Remove the First Element

Similar to pop(), the shift() method removes the first element from an array, modifies the original array, and returns the removed element.

let queue: string[] = ['Customer1', 'Customer2', 'Customer3', 'Customer4'];

// Serve the first customer in the queue
let nextCustomer = queue.shift();

console.log(queue); // Output: ['Customer2', 'Customer3', 'Customer4']
console.log(nextCustomer); // Output: 'Customer1'

Method 6: Using delete Operator (Not Recommended)

The delete operator can technically remove an item from a TypeScript array, but it leaves an undefined hole in the array, which is usually not what you want:

let colors: string[] = ['red', 'green', 'blue', 'yellow'];

// Remove 'blue' using delete
delete colors[2];

console.log(colors); // Output: ['red', 'green', empty, 'yellow']
console.log(colors.length); // Output: 4 (length doesn't change!)

As you can see, the delete operator removes the value but leaves an empty slot in the array, and the array length remains unchanged. For this reason, it’s generally better to use one of the other methods described above.

Check out Merge Object Arrays Without Duplicates in TypeScript

Method 7: Remove Duplicates from an Array

Sometimes you might want to remove duplicate items from an array. While not strictly about removing a specific item, this is a common array manipulation task:

let cities: string[] = ['New York', 'Chicago', 'Los Angeles', 'New York', 'Miami', 'Chicago'];

// Remove duplicates using Set
let uniqueCities = [...new Set(cities)];

console.log(uniqueCities); // Output: ['New York', 'Chicago', 'Los Angeles', 'Miami']

For more complex scenarios, such as removing duplicates from an array of objects, you might need to use the filter() method with a custom comparison:

let users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Sarah' },
    { id: 1, name: 'John' }, // Duplicate
    { id: 3, name: 'Mike' }
];

// Remove duplicate users based on id
let uniqueUsers = users.filter((user, index, self) =>
    index === self.findIndex(u => u.id === user.id)
);

console.log(uniqueUsers);
// Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Sarah' }, { id: 3, name: 'Mike' }]

Comparing the Methods: Which One Should You Use?

Each method has its own strengths and ideal use cases:

  1. splice(): Use when you need to modify the original array and want to remove elements at specific positions.
  2. filter(): Use when you want to keep the original array unchanged and remove elements based on a condition.
  3. slice(): Use when you want to create a new array without certain elements while preserving the original.
  4. pop(): Use when you need to remove only the last element.
  5. shift(): Use when you need to remove only the first element.
  6. Set: Use when you need to remove all duplicate values from an array.

Here’s a quick performance comparison when removing an item from a large array in TypeScript:

MethodPerformanceModifies OriginalEase of Use
splice()Slower for large arraysYesSimple
filter()FastNoSimple with conditions
slice()FastNoRequires more code
pop()Very fastYesLimited to last element
shift()Slow (re-indexes)YesLimited to first element

Check out Remove Null Values from an Array in TypeScript

TypeScript Type Considerations

When removing items from arrays in TypeScript, you might need to handle type checking appropriately. Here’s how to maintain type safety:

// For union types
let mixed: (string | number)[] = ['apple', 42, 'banana', 100];

// Type guard when filtering
let onlyStrings = mixed.filter((item): item is string => typeof item === 'string');
let onlyNumbers = mixed.filter((item): item is number => typeof item === 'number');

console.log(onlyStrings); // Output: ['apple', 'banana']
console.log(onlyNumbers); // Output: [42, 100]

This ensures your filtered arrays maintain proper type information.

I hope you found this guide helpful for understanding the various ways to remove items from arrays in TypeScript. Each method has its place, depending on your specific requirements.

If you have any questions or suggestions about working with arrays in TypeScript, feel free to leave them in the comments 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