Introduction to filter
What you'll learn: How to use filter() to create a new array containing only the elements that meet your criteria.
What Is filter()?
The filter() method examines each element in an array and creates a new array containing only the elements that pass a test you define. Think of it like a bouncer at a club—only items that meet your requirements get through to the new array.
How It Works
Just like map(), filter() takes a callback function as its argument. The key difference? Your callback must return true or false for each element:
true: Include this element in the new arrayfalse: Exclude this element
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers); // [2, 4, 6]
console.log(numbers); // [1, 2, 3, 4, 5, 6] (original unchanged)
A Practical Example
const ages = [12, 18, 25, 16, 30, 14];
const adults = ages.filter(function(age) {
return age >= 18;
});
console.log(adults); // [18, 25, 30]
The callback tested each age. Only those 18 and above returned true, so only they made it into the adults array.
Remember: Non-Mutating
Like map(), filter() never changes the original array. It always returns a brand new array with just the filtered elements.
Key Takeaway: filter() creates a new array by keeping only the elements where your callback function returns true, leaving the original array untouched.