Filtering Arrays with .filter()
Quick Overview
`.filter()` keeps every element whose test returns truthy and hands back a new array, leaving the original untouched. A test that forgets to `return` filters everything out, because `undefined` is falsy.
Deep Dive
1. Selecting Specific Items
The .filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements that pass the test condition implemented by the provided callback function.
2. Why It Matters
.filter() allows you to remove unwanted items or search array collections cleanly without writing manual for loops or mutating the source array.
3. The Pattern
Pass a callback function that returns true to keep an item, or false to discard it:
const scores = [45, 82, 91, 58, 76];
// Keep only passing scores (>= 70)
const passingScores = scores.filter((score) => score >= 70);
console.log(passingScores); // [82, 91, 76]
console.log(scores); // [45, 82, 91, 58, 76] (Original array untouched!)
4. Filtering Object Arrays & Method Chaining
Combine .filter() and .map() into a clean data processing pipeline:
const inventory = [
{ name: "Laptop", inStock: true, price: 999 },
{ name: "Phone", inStock: false, price: 500 },
{ name: "Monitor", inStock: true, price: 300 },
];
// Pipeline: Filter available items -> Map to uppercase names
const availableProductNames = inventory
.filter((item) => item.inStock)
.map((item) => item.name.toUpperCase());
console.log(availableProductNames); // ["LAPTOP", "MONITOR"]
5. Common Mistakes
- Mutating Objects Inside Filter Callback:
.filter()callbacks should be pure test functions. Avoid mutating item properties inside the filter test! - Expecting a Single Item Return:
.filter()ALWAYS returns an array (even if 0 or 1 items match). If you want to find a single matching item, use.find().
6. Try It Yourself
Write it yourself. The tests below run against your code.
Filter Passing Scores >= 70
Examples
7. Next Steps
Combine .filter() and .map() to clean data pipelines. Next, let's aggregate arrays into single values using .reduce()!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.