Common Filter Patterns
You'll learn the go-to filter recipes that show up constantly in real-world JavaScript code.
The Core Idea
While filter can test any condition, certain patterns appear over and over: removing empty or "missing" values, selecting items by their data type, and implementing text-based searches. Recognizing these patterns makes you faster and your code more readable.
Pattern 1: Removing Nullish Values
Often data contains null, undefined, or empty strings. Filter these out by testing truthiness:
const data = [1, null, 2, undefined, 3, '', 4];
const clean = data.filter(item => item);
// [1, 2, 3, 4]
// More explicit: only remove null/undefined
const keepZeros = data.filter(item => item != null);
// [1, 2, 3, '', 4]
Pattern 2: Filtering by Type
Sometimes arrays contain mixed types and you need only one kind:
const mixed = [1, 'hello', 2, true, 'world', 3];
const onlyNumbers = mixed.filter(item => typeof item === 'number');
// [1, 2, 3]
const onlyStrings = mixed.filter(item => typeof item === 'string');
// ['hello', 'world']
Pattern 3: Search Predicates
Filter objects based on text matching (like searching users by name):
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Alicia', age: 28 }
];
const searchTerm = 'ali';
const matches = users.filter(user =>
user.name.toLowerCase().includes(searchTerm.toLowerCase())
);
// [{ name: 'Alice', ... }, { name: 'Alicia', ... }]
Notice the .toLowerCase() on both sides — this makes the search case-insensitive, so 'ali' matches 'Alice'.
Key Takeaway: Filter patterns like removing nullish values, selecting by type, and text searching are your everyday tools for cleaning and querying data arrays.