CodeBlanks Logo Icon CodeBlanks

filter

Learn to filter elements matching a condition with .filter.

The filter method

The filter method returns a new array with the elements that satisfy a condition. Items that fail the condition are skipped; the original array is again left untouched.

The syntax mirrors array.map(fn): array.filter(fn). Here fn is a predicate — a function that returns a boolean (true or false) for each element. Items for which it returns true stay in the result.

Example: [1, 2, 3, 4].filter(n => n > 2) returns [3, 4], because only 3 and 4 are greater than 2.

filter and predicate

The function passed to filter is called a predicate. It returns a boolean: true keeps the element, false drops it.

The predicate can use the element itself; for example, to keep adults from a list of ages you write ages.filter(age => age >= 18). The more complex the condition, the more readable the predicate should be.

If no element matches, filter returns an empty array — it does not return null or throw. You can rely on this.

Practice Pick the expensive books

Define an array of prices [120, 45, 200, 80]. Use filter to build a new array with only the prices greater than 100, and print the result with console.log.

Starter code

index.js
const prices = [120, 45, 200, 80];
// Filter prices above 100 and print

Sample solution

index.js
const prices = [120, 45, 200, 80];
const expensive = prices.filter(p => p > 100);
console.log(expensive);

Expected output

[ 120, 200 ]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Filter values above two

Question
const nums = [1, 2, 3, 4];
const big = nums.filter(n => n ____ 2);
Answer
const nums = [1, 2, 3, 4];
const big = nums.filter(n => n > 2);

Explanation: Only values greater than 2 stay; the result is [3, 4].

2 What does filter return?

  • true
  • false
  • A boolean
  • A new array Correct answer

Explanation: filter always returns a new array, not a boolean.

3 Match the filter parts

Term Meaning
array.filter(fn) Filtering call
fn Predicate
true Result that keeps the item
false Result that drops the item

All lessons in Beginner