JavaScript Array.filter() Method - Select Matching Elements

Master Array.filter() to select elements that match a condition. Includes examples for filtering objects, chaining with map, and TypeScript type narrowing. Free reference.

Iteration

Detailed Explanation

Understanding Array.filter()

Array.filter() creates a new array containing only the elements that pass a test implemented by the provided callback function. Elements that return a truthy value are kept; those that return falsy are excluded.

Syntax

const filtered = array.filter((element, index, array) => {
  // return true to keep, false to exclude
});

Basic Examples

// Keep only even numbers
const nums = [1, 2, 3, 4, 5, 6];
const evens = nums.filter(n => n % 2 === 0);
// evens: [2, 4, 6]

// Filter objects by property
const users = [
  { name: "Alice", active: true },
  { name: "Bob", active: false },
  { name: "Carol", active: true }
];
const activeUsers = users.filter(u => u.active);
// activeUsers: [{name:"Alice",...}, {name:"Carol",...}]

Chaining filter with map

A very common pattern is to filter then transform:

const products = [
  { name: "Widget", price: 25, inStock: true },
  { name: "Gadget", price: 50, inStock: false },
  { name: "Doohickey", price: 15, inStock: true }
];

const affordableNames = products
  .filter(p => p.inStock && p.price < 30)
  .map(p => p.name);
// affordableNames: ["Widget", "Doohickey"]

TypeScript Type Narrowing

In TypeScript, filter can narrow union types using a type predicate:

const mixed: (string | null)[] = ["a", null, "b", null, "c"];
const strings: string[] = mixed.filter(
  (x): x is string => x !== null
);
// strings: ["a", "b", "c"] — properly typed as string[]

filter() vs find()

  • filter() returns all matching elements as a new array
  • find() returns only the first match (or undefined)

Use find() when you need a single result for better performance.

Use Case

Use filter() for search functionality, removing deleted items from lists, extracting subsets of data for display, and any scenario where you need to select elements that match specific criteria without mutating the original array.

Try It — JavaScript Array Methods Reference

Open full tool