How to Remove Items from Arrays in TypeScript
You're working with an array of items from an API response, and you need to remove a specific entry. Should you use splice, filter, or something else? Each method has different performance characteristics and side effects, and picking the wrong one can lead to bugs or slow code.
In this guide, we'll cover the practical methods for removing items from TypeScript arrays. You'll learn when to use mutating methods like splice versus immutable approaches like filter, how to avoid common pitfalls, and which techniques offer the best performance for different scenarios.
10 Ways to Remove Items from Arrays
1. Using the splice Method
The splice method modifies the original array by removing elements at a specific index. It's your go-to when you need to mutate an array in place:
let cartItems: string[] = ['laptop', 'mouse', 'keyboard'];
cartItems.splice(1, 1); // Removes 1 element at index 1
console.log(cartItems); // Output: ['laptop', 'keyboard']
The first parameter is the starting index, and the second is the number of elements to remove. If you need to remove multiple consecutive items, just increase that second parameter:
let products: string[] = ['phone', 'charger', 'case', 'screen protector'];
products.splice(1, 2); // Removes 'charger' and 'case'
console.log(products); // Output: ['phone', 'screen protector']
2. Using the filter Method
The filter method creates a new array containing only elements that pass a test. Unlike splice, it leaves the original array untouched:
let orderIds: number[] = [101, 102, 103, 104, 105];
let filteredOrders: number[] = orderIds.filter(id => id !== 103);
console.log(filteredOrders); // Output: [101, 102, 104, 105]
console.log(orderIds); // Output: [101, 102, 103, 104, 105] - original unchanged
This immutable approach is safer in React components, Redux reducers, or anywhere you need to preserve the original data.
3. Removing an Item by Value
When you don't know the index but you know the value, filter gives you a straightforward solution:
let statusList: string[] = ['pending', 'approved', 'rejected', 'processing'];
let filteredStatus: string[] = statusList.filter(status => status !== 'rejected');
console.log(filteredStatus); // Output: ['pending', 'approved', 'processing']
This works well with TypeScript arrays of primitive values and safely handles cases where the value doesn't exist (it just returns all elements).
4. Using indexOf and splice Together
If you need to remove a specific value but want to mutate the array in place, combine indexOf with splice:
let activeUsers: string[] = ['alice', 'bob', 'charlie'];
let index: number = activeUsers.indexOf('bob');
if (index !== -1) {
activeUsers.splice(index, 1);
}
console.log(activeUsers); // Output: ['alice', 'charlie']
The check for index !== -1 is important since indexOf returns -1 when the value isn't found. Without this check, you'd accidentally remove the last element.
5. Using findIndex for Complex Objects
When working with arrays of objects, findIndex lets you search by any property:
interface CartItem {
productId: number;
name: string;
quantity: number;
}
let cart: CartItem[] = [
{ productId: 101, name: 'Laptop', quantity: 1 },
{ productId: 102, name: 'Mouse', quantity: 2 }
];
let index: number = cart.findIndex(item => item.productId === 102);
if (index !== -1) {
cart.splice(index, 1);
}
console.log(cart); // Output: [{ productId: 101, name: 'Laptop', quantity: 1 }]
This is much cleaner than manually looping through the array. The predicate function can check any condition you need, making it flexible for complex data structures in TypeScript.
6. Removing Multiple Items
When you need to exclude several values at once, filter combined with includes works well:
let taskIds: number[] = [1, 2, 3, 4, 5];
let completedIds = [2, 4];
let remainingTasks: number[] = taskIds.filter(id => !completedIds.includes(id));
console.log(remainingTasks); // Output: [1, 3, 5]
For larger arrays, using a Set for the exclusion list is faster since lookups are O(1) instead of O(n):
let allProducts: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const discontinued = new Set([2, 4, 6, 8]);
let activeProducts: number[] = allProducts.filter(id => !discontinued.has(id));
console.log(activeProducts); // Output: [1, 3, 5, 7, 9, 10]
7. Removing the Last Item with pop()
The pop() method is the fastest way to remove the last element from an array. It modifies the array in place and returns the removed element:
let notifications: string[] = ['Email sent', 'File uploaded', 'Task completed'];
let lastNotification = notifications.pop();
console.log(lastNotification); // Output: 'Task completed'
console.log(notifications); // Output: ['Email sent', 'File uploaded']
This is perfect for stack-like data structures or when you're processing items from the end of an array.
8. Removing the First Item with shift()
The shift() method removes the first element and shifts all remaining elements down by one index:
let queue: string[] = ['first', 'second', 'third'];
let processed = queue.shift();
console.log(processed); // Output: 'first'
console.log(queue); // Output: ['second', 'third']
While shift() works well for queue operations, keep in mind it's slower than pop() for large arrays since it needs to reindex all remaining elements.
9. Using slice for Immutable Removal
If you need to remove the first or last item without mutating the original array, slice creates a new array:
let tags: string[] = ['urgent', 'review', 'completed'];
// Create new array without first item
let withoutFirst: string[] = tags.slice(1);
console.log(withoutFirst); // Output: ['review', 'completed']
// Create new array without last item
let withoutLast: string[] = tags.slice(0, -1);
console.log(withoutLast); // Output: ['urgent', 'review']
console.log(tags); // Output: ['urgent', 'review', 'completed'] - unchanged
This approach fits well with TypeScript in functional programming patterns where immutability is preferred.
10. Using toSpliced() for Modern Immutable Removal
TypeScript 5.2 introduced toSpliced(), an immutable version of splice() that returns a new array instead of modifying the original:
let items: string[] = ['one', 'two', 'three', 'four'];
// Remove 1 element at index 1
let newItems: string[] = items.toSpliced(1, 1);
console.log(newItems); // Output: ['one', 'three', 'four']
console.log(items); // Output: ['one', 'two', 'three', 'four'] - unchanged
This method is part of ES2023 and works great in functional programming contexts. You'll need TypeScript 5.2+ and to include "ES2023.Array" in your tsconfig.json:
{
"compilerOptions": {
"lib": ["ES2023.Array"]
}
}
Methods to Avoid
Never Use the delete Operator on Arrays
You might be tempted to use the delete operator to remove array elements, but this creates serious problems:
let items: string[] = ['a', 'b', 'c', 'd'];
delete items[1]; // Don't do this!
console.log(items); // Output: ['a', <empty item>, 'c', 'd']
console.log(items.length); // Output: 4 - length unchanged!
console.log(items[1]); // Output: undefined
The delete operator leaves a "hole" in the array:
- The array length doesn't update
- The element becomes
undefinedbut the index still exists - It can cause performance issues
- Iterating over the array becomes unpredictable
Always use splice(), filter(), or other proper array methods instead.
Performance Considerations
Understanding the time complexity of different removal methods helps you choose the right approach for your use case.
O(1) Operations (Constant Time)
pop() is the fastest removal method because it only affects the last element:
let items = [1, 2, 3, 4, 5];
items.pop(); // O(1) - instant regardless of array size
O(n) Operations (Linear Time)
Most other methods scale with array size:
shift(): Removes first element but must reindex all remaining elementssplice(): When removing by index, must shift all elements after the removed onefilter(): Must iterate through every element in the arrayindexOf()+splice(): indexOf searches through the array (O(n)), then splice reindexes (O(n))
When to Use Each Method
// Use pop() for last element - fastest
let stack = [1, 2, 3];
stack.pop(); // O(1)
// Use splice() when you know the index
let items = ['a', 'b', 'c'];
items.splice(1, 1); // O(n) but faster than filter for single removals
// Use filter() for multiple removals or conditions
let numbers = [1, 2, 3, 4, 5];
let evens = numbers.filter(n => n % 2 === 0); // O(n) but clean and readable
For large arrays where you're removing many items by value, using a Set for lookups makes filter operations more efficient:
let largeArray = Array.from({ length: 10000 }, (_, i) => i);
let toRemove = new Set([100, 500, 1000, 5000]);
// Set.has() is O(1), making total operation O(n) instead of O(n²)
let filtered = largeArray.filter(n => !toRemove.has(n));
Common Challenges and Solutions
Removing an Item by Value Safely
When you're not sure if a value exists in the array, filter handles this gracefully:
let apiEndpoints: string[] = ['/users', '/posts', '/comments'];
// Safe removal with filter - works even if endpoint doesn't exist
let filteredEndpoints: string[] = apiEndpoints.filter(
endpoint => endpoint !== '/admin'
);
console.log(filteredEndpoints); // Output: ['/users', '/posts', '/comments']
The filter method never throws an error; it simply returns all elements if none match the exclusion criteria.
Working with Complex Objects
When removing items from arrays of objects, identify elements by their properties:
interface TodoItem {
id: number;
title: string;
completed: boolean;
}
let todos: TodoItem[] = [
{ id: 1, title: 'Write docs', completed: true },
{ id: 2, title: 'Review PR', completed: false },
{ id: 3, title: 'Fix bug', completed: true }
];
// Remove completed todos
let activeTodos: TodoItem[] = todos.filter(todo => !todo.completed);
console.log(activeTodos);
// Output: [{ id: 2, title: 'Review PR', completed: false }]
This pattern works well when working with TypeScript and data validation.
Key Takeaways
Here's a quick reference for choosing the right removal method:
For mutating the array:
- Use
pop()to remove the last element (fastest, O(1)) - Use
shift()to remove the first element (O(n)) - Use
splice()when you know the index (O(n)) - Use
indexOf()+splice()to remove by value (O(n))
For creating a new array:
- Use
filter()to exclude elements by condition (O(n)) - Use
slice()to remove first/last elements (O(n)) - Use
toSpliced()for modern immutable removal (O(n), requires ES2023)
Never use the delete operator on arrays.
Remember, splice modifies in place while filter creates a new array. Choose based on whether you need mutability or immutability in your code. For large-scale removals, combine filter with a Set for better performance.