If map() is about transforming every item in an array, filter() is about narrowing an array down to just the items you actually want, based on some condition. Think of it like sorting through a drawer and only pulling out the things that match what you're looking for, everything else just stays behind. It's genuinely one of the methods you'll use constantly once it clicks.
Let's go through how it works, a few real examples, and the small details that trip people up early on.
Table of Contents
The Basic Idea
let numbers = [1, 2, 3, 4, 5, 6]; let evens = numbers.filter(n => n % 2 === 0); console.log(evens); // [2, 4, 6] console.log(numbers); // [1, 2, 3, 4, 5, 6], untouchedJust like map(), filter() never changes the original array, it hands you back a completely new one with just the items that matched your condition.
The Test Has to Return True or False
The function you pass to filter() needs to return something truthy or falsy for every item, that's literally the deciding factor for whether an item makes it into the new array.let ages = [12, 25, 17, 30, 8]; let adults = ages.filter(age => age >= 18); console.log(adults); // [25, 30]Here, age >= 18 returns true for 25 and 30, so they're kept, and false for the rest, so they're left out.
A Real Example: Filtering Objects
This is where filter() genuinely proves its worth, narrowing down a list of objects based on one of their properties.
let products = [
{ name: "Laptop", price: 55000, inStock: true },
{ name: "Mouse", price: 500, inStock: false },
{ name: "Keyboard", price: 1500, inStock: true }
];
let available = products.filter(product => product.inStock);
console.log(available);
// [{ name: "Laptop", ... }, { name: "Keyboard", ... }]
let affordable = products.filter(product => product.price < 2000);
console.log(affordable);
// [{ name: "Mouse", ... }, { name: "Keyboard", ... }]
This pattern shows up everywhere in real applications, filtering a product list by availability, filtering users by role, filtering tasks by whether they're completed.Combining Conditions
You're not limited to one condition at a time, you can combine several using regular logical operators inside the test.
let inStockAndAffordable = products.filter(
product => product.inStock && product.price < 2000
);
console.log(inStockAndAffordable); // [{ name: "Keyboard", ... }]
Using filter() to Remove Instead of Keep
Since filter() is just about a condition being true or false, you can flip the logic to remove items instead of keeping them, by negating the condition.
let tasks = ["buy milk", "finish report", "call mom"]; let withoutCompleted = tasks.filter(task => task !== "buy milk"); console.log(withoutCompleted); // ["finish report", "call mom"]This is genuinely a common way to "delete" an item from an array in JavaScript, since arrays don't have a built-in remove() method, filtering out everything except what you want to keep does the job cleanly.
A Common Mistake: Forgetting What filter() Actually Keeps
This trips people up early on, it's easy to accidentally write a condition that's backwards from what you intended.let numbers = [1, 2, 3, 4, 5]; // Meant to keep numbers greater than 3, but wrote it backwards let wrong = numbers.filter(n => n < 3); console.log(wrong); // [1, 2], not what was probably intended let correct = numbers.filter(n => n > 3); console.log(correct); // [4, 5]It's a small thing, but it's worth reading your condition out loud before running it, "keep the number if it's greater than 3," and making sure your code actually says that.
filter() vs. find(): Picking the Right One
These two get confused occasionally. filter() always returns an array, even if only one item matches, or none at all. find() returns just the first matching item itself, not wrapped in an array.
let users = [{ id: 1 }, { id: 2 }, { id: 3 }];
let filtered = users.filter(u => u.id === 2);
console.log(filtered); // [{ id: 2 }], an array
let found = users.find(u => u.id === 2);
console.log(found); // { id: 2 }, just the object itself
If you know you're only looking for one specific item, find() is usually the better fit. If you genuinely want every item that matches, filter() is the right call.Conclusion
filter() does exactly one job, and it does it well, narrowing an array down to only what actually matches a condition. Once you're comfortable writing the test function correctly, and remembering it needs to return true or false for every item, it becomes one of the most natural, readable ways to work with lists of data, whether that's numbers, strings, or entire objects.Frequently Asked Questions (FAQs)
1.Does filter() change my original array?2.What happens if no items match my condition?No, it always returns a new array, leaving the original array exactly as it was.
3.Can I use filter() to remove a specific item from an array?filter() just returns an empty array, []. It won't throw an error or return undefined, so it's always safe to use the result right away.
Yes, that's actually one of its most common uses. Since JavaScript arrays don't have a built-in remove() method, filtering out everything except the item you don't want is the standard approach.
0 Comments