Topic 48 of 87
Array filter()
Overview
The .filter() method creates a new array filled with all elements that pass a logical test provided by a callback function.
If the callback returns true (or a truthy value), the element is kept. If it returns false, the element is dropped. Like .map(), it does not change the original array.
Syntax
Filtering Numbers
javascript
const ages = [32, 15, 18, 12, 40];
// Only keep ages 18 and above
const adults = ages.filter(age => age >= 18);
console.log(adults); // [32, 18, 40]Filtering Objects
javascript
const tasks = [
{ id: 1, title: "Learn JS", done: true },
{ id: 2, title: "Learn React", done: false }
];
// Keep only tasks where done === false
const pendingTasks = tasks.filter(task => !task.done);Common Pitfalls
- Assuming
.filter()modifies the original array. If you need to filter a list in place, you must reassign the variable:myList = myList.filter(...).
Interview Questions
Q:
Can
.filter() return an array larger than the original array?A:
No. .filter() can only return a new array that is the exact same size (if all items pass) or smaller. It never adds new elements.
Real-World Example
Implementing a search bar that filters a list of products dynamically as the user types.
example
javascript
const matches = products.filter(p => p.name.toLowerCase().includes(searchQuery));Check Your Knowledge
Test your understanding of Array filter() with these quick questions.