Extract specific elements from an array matching a boolean test condition using the pure, non-mutating .filter() method.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
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.
.filter() allows you to remove unwanted items or search array collections cleanly without writing manual for loops or mutating the source array.
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!)
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"]
.filter() callbacks should be pure test functions. Avoid mutating item properties inside the filter test!.filter() ALWAYS returns an array (even if 0 or 1 items match). If you want to find a single matching item, use .find().Combine .filter() and .map() to clean data pipelines. Next, let's aggregate arrays into single values using .reduce()!