filter()
filter()
Section titled “filter()”Introduction
Section titled “Introduction”filter() creates a new array with elements that pass a test function. It’s used for selection/filtering data.
Visual Explanation
Section titled “Visual Explanation”flowchart LR A["[1, 2, 3, 4, 5]"] B["filter(x => x > 2)"] C["[3, 4, 5]"]
A --> B --> CExamples
Section titled “Examples”const numbers = [1, 2, 3, 4, 5];const evens = numbers.filter(n => n % 2 === 0);// [2, 4]
const users = [ { name: 'Alice', age: 17 }, { name: 'Bob', age: 22 }];const adults = users.filter(user => user.age >= 18);// [{ name: 'Bob', age: 22 }]Summary
Section titled “Summary”- Returns filtered array with elements that pass the test
- Does NOT mutate original
- Can return fewer elements than original
- Great for search/filter interfaces