The filter()
method is a built-in higher-order function in Javascript that allows developers to iterate over an array and create a new array containing elements that meet a specified condition.
It provides a concise and efficient way to filter out elements from an array based on a given criteria, without modifying the original array.
Syntax for the filter()
method:
array.filter(callback(element[, index[, array]])[, thisArg])
Here,
-
array: This is the array on which the
filter()
method is called. It is the array that you want to filter. -
callback: This is a callback function that is executed once for each element in the array. It takes three optional arguments:
- element: This is the current element being processed in the array.
- index (optional): This is the index of the current element being processed in the array.
- array (optional): This is the array on which the filter() method is called.
-
thisArg (optional): This is an object that specifies the value of this inside the callback function. If not provided, this will refer to the global object.
The callback
function should return a boolean value, either true
or false
, which determines whether the current element should be included in the resulting filtered array.
If the callback function returns true
, the element will be included in the new array; if it returns false
, the element will be excluded.
Let’s check some usages of filter method:
1. Filtering elements based on a condition:
The most common use case of the filter()
method is to filter an array of elements based on a condition.
For example, you can use it to filter out all the even numbers from an array of integers:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = numbers.filter(function (number) {
return number % 2 === 0;
});
console.log(evens); // Output: [2, 4, 6, 8, 10]
In this example, the callback function checks if each element in the numbers
array is even using the modulo operator (%
), and returns true
for even numbers and false
for odd numbers. The filter()
method then creates a new array called evens
that contains only the even numbers from the original array.
2. Filtering elements based on object properties:
You can also use the filter()
method to filter elements based on properties of objects in an array.
For example, you can filter an array of objects representing people based on their age:
const people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 },
{ name: "Dave", age: 40 },
];
const adults = people.filter(function (person) {
return person.age >= 18;
});
console.log(adults);
/* Output:
[
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 },
{ name: 'Dave', age: 40 }
]
*/
In this example, the callback function checks if the age
property of each object in the people
array is greater than or equal to 18, and returns true
for adults and false
for minors. The filter()
method then creates a new array called adults that contains only the objects representing adults based on the age property.
3. Removing elements from an array:
Another use case of the filter()
method is to remove elements from an array that do not meet a certain condition.
For example, you can use it to remove all the null or undefined values from an array:
const arr = [1, null, 3, undefined, 5, null, 7, 8, undefined];
const filteredArr = arr.filter(function (value) {
return value !== null && value !== undefined;
});
console.log(filteredArr); // Output: [1, 3, 5, 7, 8]
In this example, the callback function checks if each element in the arr
array is not equal to null
and not equal to undefined
, and returns true
for elements that are not null
or undefined
. The filter()
method then creates a new array called filteredArr
that contains only the non-null and non-undefined values from the original array, effectively removing the null and undefined values.
4. Chaining multiple filters:
One of the powerful features of the filter()
method is that it can be chained multiple times to apply multiple filters sequentially. This allows you to create complex filtering logic based on multiple conditions.
For example, you can filter an array of products based on both price and category:
const products = [
{ name: "Shoes", price: 100, category: "Footwear" },
{ name: "Shirt", price: 50, category: "Apparel" },
{ name: "Watch", price: 250, category: "Accessories" },
{ name: "Hat", price: 30, category: "Accessories" },
{ name: "Socks", price: 10, category: "Footwear" },
];
const filteredProducts = products
.filter(function (product) {
return product.price <= 100; // Filter products with price <= 100
})
.filter(function (product) {
return product.category === "Footwear"; // Filter products with category 'Footwear'
});
console.log(filteredProducts);
/* Output:
[
{ name: 'Shoes', price: 100, category: 'Footwear' },
{ name: 'Socks', price: 10, category: 'Footwear' }
]
*/
In this example, two filter()
methods are chained together to filter the products
array first based on price, and then based on category. The resulting filteredProducts
array contains only the products with a price less than or equal to 100 and category ‘Footwear’.
5. Creating a copy of an array:
The filter()
method can also be used to create a shallow copy of an array, as it returns a new array containing the filtered elements, leaving the original array unchanged.
This can be useful when you want to manipulate an array without modifying the original data.
For example:
const numbers = [1, 2, 3, 4, 5];
const filteredNumbers = numbers.filter(function (number) {
return number > 2; // Filter numbers greater than 2
});
console.log(filteredNumbers); // Output: [3, 4, 5]
console.log(numbers); // Output: [1, 2, 3, 4, 5]
In this example, the numbers
array remains unchanged, and the filteredNumbers
array contains only the numbers greater than 2.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.