Removing Elements with .filter()
You'll learn how to create a new array with unwanted elements removed using .filter() instead of mutating the original array with .splice().
The Core Idea
When you need to remove elements from an array immutably, .filter() is your go-to method. Instead of changing the original array (like .splice() does), .filter() creates a new array containing only the elements that pass a test you define.
Think of .filter() as a bouncer at a club: each element approaches, the bouncer applies your test function, and only elements that pass get into the new array. The original line of people remains unchanged.
How It Works
The .filter() method takes a predicate function that returns true for elements you want to keep and false for elements you want to remove. The result is a brand new array:
const numbers = [1, 2, 3, 4, 5];
// Remove all even numbers (keep odd ones)
const oddOnly = numbers.filter(num => num % 2 !== 0);
console.log(oddOnly); // [1, 3, 5]
console.log(numbers); // [1, 2, 3, 4, 5] - original unchanged
Removing by Value
const colors = ['red', 'blue', 'green', 'blue'];
// Remove all instances of 'blue'
const noBlue = colors.filter(color => color !== 'blue');
console.log(noBlue); // ['red', 'green']
Removing by Condition
const scores = [45, 78, 92, 33, 88];
// Remove failing scores (below 50)
const passing = scores.filter(score => score >= 50);
console.log(passing); // [78, 92, 88]
Key Takeaway: Use .filter() to immutably remove elements by keeping only those that pass your test function — the original array stays untouched and you get a fresh array with unwanted elements excluded.