The filter() method in JavaScript
Details, examples, practice
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:
array.filter(function(element, index, array) {
// if the condition is true, the element remains in the new array
return condition;
});
Parameters
Return Value
A new array containing only the elements that return true.
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.
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.
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 }
]
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);
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]
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.