Chapter VIII · Arrays

filter

The filter method creates a shallow copy of a portion of a given array containing only elements that pass a test condition.

01 How It Works

Think of a security checkpoint gate allowing only items meeting specific criteria to pass.

The callback returns a boolean; truthy values keep the item, falsy values discard it.

example.js
const nums = [1, 2, 3, 4];
const evens = nums.filter(n => n % 2 === 0); // [2, 4]
  1. 1. Call .filter() on an array.

  2. 2. Supply a condition test callback function.

  3. 3. Collect matching elements into a new filtered array.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
const scores = [45, 80, 65, 90];
const passed = scores.filter(s => s >= 60);

Key Takeaway

Filter extracts subsets of data matching specific boolean conditions.

Related Concepts