filter()

ES5+

Creates a new array with all elements that pass the test implemented by the provided function.

Syntax

array.filter(callback(element, index, array), thisArg)

Parameters

callback Function

Function to test each element of the array

Return Value

Array

A new array with elements that pass the test

Examples

JavaScript
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(x => x % 2 === 0);
console.log(evens);
Output:
// [2, 4, 6]

📌 When to Use

Use filter() when you need to select a subset of elements from an array based on a condition. Perfect for searching, removing unwanted items, or extracting elements that match specific criteria.

⚠️ Common Mistakes

Using filter() to find a single element - use find() instead for better performance

Returning truthy/falsy values instead of explicit booleans (works but less readable)

Expecting filter() to modify the original array - it always creates a new one

✅ Best Practices

Combine with map() for transform-then-filter or filter-then-transform patterns

Use descriptive callback names or comments for complex filtering logic

For removing falsy values, use: arr.filter(Boolean)

⚡ Performance Notes

filter() iterates through all elements even after finding matches. For large arrays where you only need the first match, use find(). filter() creates a new array, so chaining multiple filters is less efficient than a single filter with combined conditions.

🌍 Real World Example

Filtering Products by Search and Category

Filter an e-commerce product list based on user search input and selected category

const products = await fetchProducts();
const searchTerm = 'laptop';
const category = 'electronics';

const filtered = products.filter(product =>
  product.category === category &&
  product.name.toLowerCase().includes(searchTerm.toLowerCase()) &&
  product.inStock
);
// Only shows in-stock laptops in electronics category

Related Methods