Keep What Matches
filter returns a new array with only the items that pass the test.
It never mutates the original array.
JavaScript Tutorial
filter selects items that match a condition and returns a new array.
It is the go-to method for searching and selecting data.
Filtering is common in UI lists, search results, and data validation.
filter makes the intent clear and the code concise.
array.filter((value, index, array) => condition)const nums = [1, 2, 3, 4];
const evens = nums.filter((n) => n % 2 === 0);
console.log(evens);Keep only even numbers.
const users = [{ active: true }, { active: false }];
const active = users.filter((u) => u.active);
console.log(active);Filter arrays of objects by a field.
filter returns a new array with only the items that pass the test.
It never mutates the original array.
Use filter to express selection rules clearly.
Combine it with map for powerful data pipelines.
If nothing matches, filter returns an empty array.
Always handle that case if needed.
const names = ["ava", "liam", "noah"];
const result = names.filter((n) => n.includes("a"));
console.log(result);Use string checks inside filter.
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.
Without
const out = [];
for (const n of nums) {
if (n % 2 === 0) out.push(n);
}With
const out = nums.filter((n) => n % 2 === 0);Avoid modifying items while filtering.
Use find when you need the first match.
Handle no matches gracefully.
A new array with items that pass the test.
Use find instead of filter.
No, it returns a new array.
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);No, it returns a new array.
An empty array.
Yes, often with map or reduce.
Try filtering with different conditions.