JavaScript
This page explains how filter() creates a new array containing only the elements that satisfy a condition.
Goal: keep the elements whose callback returns true, without changing the original array.
filter()
Use filter() when you want all matching elements, such as all even numbers or all users above a certain age. The callback runs once for each element.
A small example
JavaScript
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
console.log(numbers); // [1, 2, 3, 4, 5, 6]The expression number % 2 === 0 returns true for even numbers, so only those numbers are copied into the new array.
Filtering objects
JavaScript
const users = [
{ name: "Aki", age: 17 },
{ name: "Ren", age: 22 }
];
const adults = users.filter(user => user.age >= 18);
// [{ name: "Ren", age: 22 }]Common uses and cautions
- Extract records that match a search or status.
- Remove empty strings or unwanted values with an explicit condition.
filter()returns all matches, not just the first one.- Use
find()when you need the first matching element. - The original array is not changed, but the objects inside it are not deeply cloned.