Codectionary / Developer documentation / JavaScript

filter()

filter() creates a new array containing only the elements that pass a test function, without modifying the original array. It is one of the most commonly used array methods, ideal for narrowing down a collection based on some condition.

Syntax

arr.filter(item => condition)

Examples

Basic Filtering

Selecting elements that meet a condition.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6, 8, 10]

const greaterThan5 = numbers.filter(n => n > 5);
console.log(greaterThan5); // [6, 7, 8, 9, 10]

Filtering Objects by Property

A very common real-world use case.

const products = [
  { name: "Laptop", price: 999, inStock: true },
  { name: "Mouse", price: 25, inStock: false },
  { name: "Keyboard", price: 75, inStock: true }
];

const available = products.filter(p => p.inStock);
console.log(available.map(p => p.name)); // ["Laptop", "Keyboard"]

const affordable = products.filter(p => p.price < 100);
console.log(affordable.map(p => p.name)); // ["Mouse", "Keyboard"]

Chaining with map()

Combining filter() and map() to select and transform in sequence.

const numbers = [1, 2, 3, 4, 5, 6];

const result = numbers
  .filter(n => n % 2 === 0)  // [2, 4, 6]
  .map(n => n * n);          // [4, 16, 36]

console.log(result); // [4, 16, 36]

Best practices

  • Use filter() to select a subset of an array based on a condition - it always returns a new array, even if empty
  • Chain filter() with map() for a clean, readable pipeline of narrowing then transforming data
  • Remember filter() always returns an array (possibly empty), unlike find() which returns a single element or undefined
  • Avoid mutating the original array or its elements inside the filter callback - keep the test function pure

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation