Course contentsShow
← JavaScript
Lesson 1759 of 2,72337. Functional Programming PatternsFree lesson

Immutable Array Updates: Removing Elements

Remove elements immutably using filter and slice instead of splice or pop.

Immutable Array Updates: Removing Elements

You'll learn how to remove elements from arrays without mutating the original array using filter() and slice().

The Core Idea

When working with immutability, you cannot use mutating methods like splice(), pop(), shift(), or direct index deletion. Instead, you create a new array that contains only the elements you want to keep.

Think of it like editing a document: rather than erasing words on the original paper, you create a fresh copy with those words omitted. The original stays intact.

Using filter() to Remove by Condition

The filter() method is perfect when you want to remove elements based on a condition:

const numbers = [10, 20, 30, 40, 50];

// Remove all values greater than 30
const filtered = numbers.filter(num => num <= 30);
// filtered is [10, 20, 30]
// numbers is still [10, 20, 30, 40, 50]

// Remove a specific value
const removed = numbers.filter(num => num !== 30);
// removed is [10, 20, 40, 50]

Using slice() to Remove by Index

When you know the exact index to remove, combine two slice() calls:

const letters = ['a', 'b', 'c', 'd', 'e'];

// Remove element at index 2
const indexToRemove = 2;
const result = [
  ...letters.slice(0, indexToRemove),
  ...letters.slice(indexToRemove + 1)
];
// result is ['a', 'b', 'd', 'e']
// letters is unchanged

You're essentially taking everything before the index and everything after it, skipping the element itself.

Key Takeaway: Remove array elements immutably with filter() for condition-based removal or slice() for index-based removal—both return new arrays and leave the original untouched.