Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript filter()

filter selects items that match a condition and returns a new array.

It is the go-to method for searching and selecting data.

Why We Need It

Filtering is common in UI lists, search results, and data validation.

filter makes the intent clear and the code concise.

Syntax

array.filter((value, index, array) => condition)

Basic Example

1. Basic filter

const nums = [1, 2, 3, 4];
const evens = nums.filter((n) => n % 2 === 0);

console.log(evens);

Keep only even numbers.

Real World Example

2. Filter objects

const users = [{ active: true }, { active: false }];
const active = users.filter((u) => u.active);

console.log(active);

Filter arrays of objects by a field.

Multiple Use Cases

Keep What Matches

filter returns a new array with only the items that pass the test.

It never mutates the original array.

Short and Clear

Use filter to express selection rules clearly.

Combine it with map for powerful data pipelines.

Empty Results

If nothing matches, filter returns an empty array.

Always handle that case if needed.

More Examples

3. Filter by search

const names = ["ava", "liam", "noah"];
const result = names.filter((n) => n.includes("a"));

console.log(result);

Use string checks inside filter.

4. Chain with map

const nums = [1, 2, 3, 4];
const doubledEvens = nums.filter((n) => n % 2 === 0).map((n) => n * 2);

console.log(doubledEvens);

Filter first, then transform.

Comparison

Without

const out = [];
for (const n of nums) {
  if (n % 2 === 0) out.push(n);
}

With

const out = nums.filter((n) => n % 2 === 0);

Common Mistakes and Fixes

Mutating in filter

Avoid modifying items while filtering.

Expecting one item

Use find when you need the first match.

Forgetting empty array

Handle no matches gracefully.

Interview Questions

What does filter return?

A new array with items that pass the test.

How do you get the first match?

Use find instead of filter.

Does filter mutate?

No, it returns a new array.

Practice Problem

Practice: Filter a list of numbers to keep only values greater than 10.

const nums = [4, 12, 9, 18];
// TODO: filter > 10

One Possible Solution

const nums = [4, 12, 9, 18];
const result = nums.filter((n) => n > 10);
console.log(result);

Frequently Asked Questions

Does filter mutate the array?

No, it returns a new array.

What does filter return if no items match?

An empty array.

Can filter be chained?

Yes, often with map or reduce.

Try It Yourself

Try filtering with different conditions.