The filter() Method in JavaScript
The filter() method is one of the most important methods in JavaScript, used to select only those elements from an array that meet a certain condition. This method allows you to easily obtain a new array containing only the matching elements without modifying the original array.
In this article, we will learn:
- What the filter() method is
- How it works
- What it returns
- How it differs from map()
- How to write filter from scratch
Syntax
array.filter(function(element, index, array) {
// if the condition is true, the element remains in the new array
return condition;
});
Parameters
- element – the current element
- index – the current index
- array – the entire array
Return Value
A new array containing only the elements that return true.
Simple Example
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers); // [2, 4, 6]
The explanation is simple: in this case, we only took the elements that belong to the category of even numbers.
Difference from map()
- map() returns a new array consisting of the values obtained through the callback.
- filter() returns a new array containing only the elements that matched a certain condition.
const nums = [1, 2, 3, 4, 5, 6];
const doubled = nums.map(n => n * 2); // map() - doubles each element
const evens = nums.filter(n => n % 2 === 0); // filter() - selects only even numbers
console.log(doubled); // [2, 4, 6, 8, 10, 12]
console.log(evens); // [2, 4, 6]
map transforms all elements, while filter selects only the matching ones.
Key Features
- Returns a new array without modifying the original array.
- If no elements match the condition, an empty array [] is returned.
- Can be used with more complex conditions, either individually or combined.
Real-World Example
For example, in my blog, I have paragraphs from several pages, and I want to retrieve only the last non-deleted pages:
const pages = [
{ id: 1, title: 'Home', isDeleted: false },
{ id: 2, title: 'About', isDeleted: true },
{ id: 3, title: 'Contact', isDeleted: false },
{ id: 4, title: 'Blog', isDeleted: false }
];
const activePages = pages.filter(page => !page.isDeleted);
console.log(activePages);
Result:
[
{ id: 1, title: 'Home', isDeleted: false },
{ id: 3, title: 'Contact', isDeleted: false },
{ id: 4, title: 'Blog', isDeleted: false }
]
How the filter() Method Works Internally
filter is a method associated with Array.prototype.
When we write:
[1, 2, 3, 4].filter(fn);
It is the same as:
Array.prototype.filter.call([1, 2, 3, 4], fn);
Let’s Write Our Own myFilter() Function
function myFilter(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
if (callback(array[i], i, array)) {
result.push(array[i]);
}
}
return result;
}
Usage:
const nums = [1, 2, 3, 4, 5, 6];
const evenNumbers = myFilter(nums, function(num) {
return num % 2 === 0;
});
console.log(evenNumbers); // [2, 4, 6]
We Can Add It to the Array (for Educational Purposes)
Array.prototype.myFilter = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};
Usage:
const evenNumbers = [1, 2, 3, 4, 5, 6].myFilter(n => n % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
Reminder: Avoid modifying prototypes in a production environment.