Master JavaScript array filter() method: syntax, callback, filtering objects, chaining, remove falsy values, duplicates, real-world use cases, and interview Q&A.
The filter() method creates a brand-new array containing only the elements that pass your test (return true from the callback). It never touches the original array.
Visual: How filter() Works
Original: [1, 2, 3, 4, 5, 6]
↓
callback: n % 2 === 0
↓
Test each: ✗ ✓ ✗ ✓ ✗ ✓
↓
New Array: [2, 4, 6]
Original: [1, 2, 3, 4, 5, 6] ← unchanged!
Basic Examples
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Keep even numbers
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens);
// Keep numbers greater than 5
const large = numbers.filter(n => n > 5);
console.log(large);
// Original is untouched
console.log(numbers);
[2, 4, 6, 8, 10]
[6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Filtering Strings
const words = ["apple", "banana", "kiwi", "strawberry", "fig", "mango"];
// Keep words longer than 5 characters
const long = words.filter(w => w.length > 5);
console.log(long);
// Keep words that contain the letter "a"
const withA = words.filter(w => w.includes("a"));
console.log(withA);
// Keep words starting with a vowel
const vowelStart = words.filter(w => "aeiou".includes(w[0]));
console.log(vowelStart);
["banana", "strawberry", "mango"]
["banana", "strawberry", "mango"]
["apple"]
Filtering Arrays of Objects
const products = [
{ name: "Laptop", price: 999, category: "electronics", inStock: true },
{ name: "Shirt", price: 29, category: "clothing", inStock: true },
{ name: "Phone", price: 699, category: "electronics", inStock: false },
{ name: "Pants", price: 59, category: "clothing", inStock: true },
{ name: "Tablet", price: 499, category: "electronics", inStock: true }
];
// Filter by category
const electronics = products.filter(p => p.category === "electronics");
console.log(electronics.map(p => p.name));
// Filter by stock + price
const deals = products.filter(p => p.inStock && p.price < 500);
console.log(deals.map(p => p.name));
// Filter out unavailable
const available = products.filter(p => p.inStock);
console.log(available.length);
["Laptop", "Phone", "Tablet"]
["Shirt", "Pants", "Tablet"]
4
Remove Falsy Values
const messy = [0, 1, false, 2, "", 3, null, undefined, NaN, 4, "hello"];
// Remove ALL falsy values (uses Boolean as predicate)
const clean = messy.filter(Boolean);
console.log(clean);
// Remove only null/undefined (keep 0, false, "")
const noNullish = messy.filter(item => item != null);
console.log(noNullish);
[1, 2, 3, 4, "hello"]
[0, 1, false, 2, "", 3, NaN, 4, "hello"]
Remove Duplicates with filter
const arr = [1, 2, 2, 3, 3, 3, 4, 5, 5];
// Keep only first occurrence
const unique = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(unique);
// Find the duplicates
const duplicates = arr.filter((item, index) => arr.indexOf(item) !== index);
console.log([...new Set(duplicates)]);
[1, 2, 3, 4, 5]
[2, 3, 5]
Using Index in filter
const items = ["a", "b", "c", "d", "e", "f"];
// Keep elements at even indices
const evenIdx = items.filter((_, i) => i % 2 === 0);
console.log(evenIdx);
// Keep first 3 elements
const first3 = items.filter((_, i) => i < 3);
console.log(first3);
["a", "c", "e"]
["a", "b", "c"]
Chaining filter with Other Methods
const employees = [
{ name: "Alice", dept: "Engineering", salary: 120000, years: 5 },
{ name: "Bob", dept: "Marketing", salary: 75000, years: 3 },
{ name: "Carol", dept: "Engineering", salary: 95000, years: 2 },
{ name: "Dave", dept: "Marketing", salary: 85000, years: 7 },
{ name: "Eve", dept: "Engineering", salary: 105000, years: 4 }
];
// Engineering employees with > 3 years, get their names sorted
const result = employees
.filter(e => e.dept === "Engineering" && e.years > 3)
.map(e => e.name)
.sort();
console.log(result);
Real World Use Cases
// 1. Search/filter UI
function searchProducts(products, query) {
const q = query.toLowerCase();
return products.filter(p =>
p.name.toLowerCase().includes(q) ||
p.category.toLowerCase().includes(q)
);
}
// 2. Active users only
const users = [
{ id: 1, name: "Alice", active: true },
{ id: 2, name: "Bob", active: false },
{ id: 3, name: "Carol", active: true }
];
const activeUsers = users.filter(u => u.active);
console.log(activeUsers.map(u => u.name));
// 3. Clean API response (remove deleted items)
const apiData = [
{ id: 1, title: "Post 1", deleted: false },
{ id: 2, title: "Post 2", deleted: true },
{ id: 3, title: "Post 3", deleted: false }
];
const visible = apiData.filter(item => !item.deleted);
console.log(visible.length);
// 4. Price range filter (e-commerce)
const priceFilter = (products, min, max) =>
products.filter(p => p.price >= min && p.price <= max);
Common Mistakes
| ❌ Wrong | ✅ Correct | Why |
|---|
arr.filter(item => item) when 0 is valid data | arr.filter(item => item !== null && item !== undefined) | 0 is falsy and would be removed by first version |
Returning the element: arr.filter(item => item.name) expecting a boolean | It works — any truthy value keeps the element | But explicit booleans (===, !==) are clearer |
arr.filter(item => item.id === 5)[0] when you want one item | Use arr.find(item => item.id === 5) | find() short-circuits; filter() scans the whole array |
Expecting filter() to stop early | It always checks every element | Use find() if you only need the first match |
Mutating objects inside filter() | Filter only — no mutations in callbacks | Side effects inside filter cause hidden bugs |
filter() vs find() vs some()
| Feature | filter() | find() | some() |
|---|
| Returns | New array | First matching element | Boolean |
| Stops early? | No | Yes ✅ | Yes ✅ |
| Use when | You want ALL matches | You want ONE item | You just need to check existence |
| Empty result | [] | undefined | false |
const nums = [10, 25, 30, 45, 50];
console.log(nums.filter(n => n > 20)); // [25, 30, 45, 50] — all matches
console.log(nums.find(n => n > 20)); // 25 — first match
console.log(nums.some(n => n > 20)); // true — exists?
Cheat Sheet
Basic filter: arr.filter(n => n > 0)
Filter objects: arr.filter(obj => obj.active)
Remove falsy: arr.filter(Boolean)
Remove nullish: arr.filter(v => v != null)
Remove duplicates: arr.filter((v, i) => arr.indexOf(v) === i)
Filter by index: arr.filter((_, i) => i % 2 === 0)
Multi-condition: arr.filter(v => v > 0 && v < 100)
Chain with map: arr.filter(v => v > 0).map(v => v * 2)
Interview Questions
Q1. What does filter() return?
Always a new array (never undefined). If no elements pass the test, it returns an empty array [].
Q2. Does filter() mutate the original array?
No. filter() is a non-mutating method. It always returns a brand-new array.
Q3. What is the difference between filter() and find()?
filter() returns an array of all matching elements and checks every element. find() returns the first matching element (not an array) and stops as soon as it finds a match. Use find() when you need just one item — it's more efficient.
Q4. How do you filter an array of objects by a nested property?
const users = [{ name: "Alice", address: { city: "Delhi" } }];
const delhi = users.filter(u => u.address.city === "Delhi");
Q5. What happens if the filter callback has no return statement?
An implicit return undefined causes undefined to be treated as falsy — the element is discarded. Every element will be removed from the result.
Q6. Can you break out of a filter() loop early?
No. filter() always iterates through the entire array. If you only need the first match, use find() instead.
Q7. How do you filter out duplicate objects by a specific property?
const arr = [{id: 1, name: "A"}, {id: 2, name: "B"}, {id: 1, name: "C"}];
const unique = arr.filter((item, index, self) =>
index === self.findIndex(t => t.id === item.id)
);
// [{id: 1, name: "A"}, {id: 2, name: "B"}]
Key Takeaways
filter() always returns a new array — original is never changed- The callback must return a truthy value to keep an element
- Use
filter(Boolean) to remove all falsy values quickly - For a single item, prefer
find() — it short-circuits and is faster - You can chain
.filter().map().reduce() for powerful data pipelines - Avoid mutations inside the filter callback — keep it pure