JavaScript filter
is a built-in array method that allows you to create a new array containing elements from the original array that meet a specific condition. It is a powerful tool for filtering data and is commonly used for data manipulation and extracting specific elements from arrays.
Here’s an in-depth explanation of the filter
method:
Syntax fo JavaScript filter
:
const newArray = array.filter(callback(element, index, array));
array
: The original array you want to filter.callback
: A function that is executed for each element in the array.element
: The current element being processed in the array.index
(optional): The index of the current element in the array.array
(optional): The array on whichfilter
was called.
Return Value:
- The
filter
method returns a new array containing all elements from the original array that satisfy the condition specified in thecallback
function.
How it works:
- For each element in the array, the
callback
function is called. - If the
callback
function returnstrue
for an element, that element is included in the new array. If thecallback
returnsfalse
, the element is excluded.
Key Points:
- Non-Destructive: The
filter
method does not modify the original array. It creates a new array with the filtered elements, leaving the original array intact. - Callback Function: The
callback
function is crucial, as it defines the condition for inclusion in the new array. It should returntrue
for elements that should be kept andfalse
for elements that should be removed. - Index and Array (optional): The
index
andarray
parameters in thecallback
function are optional and can be used for more complex filtering conditions.
Example:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
In this example, filter
is used to create a new array, evenNumbers
, which contains only the elements from the numbers
array that meet the condition of being even. The callback
function checks if num % 2 === 0
and includes elements that meet this condition in the evenNumbers
array.
Overall, the filter
method provides an elegant and efficient way to work with arrays, allowing you to selectively extract elements based on a wide range of conditions.
Most used Examples
Certainly, let’s go through JavaScript’s filter
function step by step with detailed explanations:
1. Basic Usage:
Filtering elements in an array based on a condition.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
In this example, the filter
method is used to create a new array, evenNumbers
, which contains only the elements from the numbers
array that meet the condition specified in the callback function (in this case, that condition is “num % 2 === 0”).
2. Filtering Objects
Filtering an array of objects.
const products = [
{ name: 'Phone', price: 500 },
{ name: 'Laptop', price: 1000 },
{ name: 'Tablet', price: 300 },
];
const affordableProducts = products.filter(product => product.price <= 500);
console.log(affordableProducts); // Output: [{ name: 'Phone', price: 500 }, { name: 'Tablet', price: 300 }]
Here, we’re using the filter
method to create a new array, affordableProducts
, containing objects from the products
array where the price
property is less than or equal to 500.
3. Using Index
Accessing the index while filtering.
const numbers = [10, 20, 30, 40, 50];
const filteredIndices = numbers.filter((num, index) => index % 2 === 0);
console.log(filteredIndices); // Output: [10, 30, 50]
In this example, filteredIndices
is an array of numbers from the numbers
array at even indices. The filter
callback function takes two arguments, the current element (num
) and its index (index
), which allows us to filter elements based on their position in the array.
4. Filtering Unique Values
Creating a new array with unique values.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.filter((num, index, array) => array.indexOf(num) === index);
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
In this case, uniqueNumbers
contains only the unique values from the numbers
array. The filter
method, combined with indexOf
, helps to eliminate duplicate values by checking if an element’s first occurrence matches its current position in the array.
5. Chaining Filters
Applying multiple filter conditions.
const employees = [
{ name: 'Alice', salary: 50000, department: 'HR' },
{ name: 'Bob', salary: 60000, department: 'Engineering' },
{ name: 'Charlie', salary: 70000, department: 'HR' },
{ name: 'David', salary: 80000, department: 'Engineering' },
];
const highPaidEngineers = employees
.filter(employee => employee.department === 'Engineering')
.filter(employee => employee.salary > 70000);
console.log(highPaidEngineers); // Output: [{ name: 'David', salary: 80000, department: 'Engineering' }]
In this example, we first filter employees by department and then by salary. The result, highPaidEngineers
, is an array containing employees who are part of the ‘Engineering’ department and have a salary greater than 70000.
These examples illustrate various use cases of the filter
method, showcasing its flexibility for extracting specific elements from arrays based on different conditions.
6. Filtering by String Length
Filtering an array of strings based on their length.
const fruits = ['apple', 'banana', 'kiwi', 'strawberry', 'cherry'];
const shortFruits = fruits.filter(fruit => fruit.length < 5);
console.log(shortFruits); // Output: ['kiwi']
In this example, the filter
method is used to create an array, shortFruits
, that contains only the fruits with a length less than 5 characters.
7. Filtering Null or Undefined Values
Filtering an array to remove null or undefined values.
const data = [42, null, 56, undefined, 23, 0, 17];
const validData = data.filter(item => item !== null && item !== undefined);
console.log(validData); // Output: [42, 56, 23, 0, 17]
Here, validData
is an array containing only the elements that are not null or undefined, effectively filtering out these falsy values.
8. Filtering with Regular Expressions
Filtering an array of strings using regular expressions.
const words = ['apple', 'banana', 'kiwi', 'strawberry', 'cherry'];
const regex = /^k/;
const startsWithK = words.filter(word => regex.test(word));
console.log(startsWithK); // Output: ['kiwi']
In this case, we use a regular expression to filter words in the words
array. The startsWithK
array contains only words that start with the letter ‘k’.
9. Filtering Using a Function
Using a custom filter function for complex conditions.
const numbers = [10, 25, 5, 30, 60, 15];
function isDivisibleBy5AndEven(num) {
return num % 5 === 0 && num % 2 === 0;
}
const filteredNumbers = numbers.filter(isDivisibleBy5AndEven);
console.log(filteredNumbers); // Output: [10, 30, 60]
In this example, the isDivisibleBy5AndEven
function defines a custom filter condition, and the filteredNumbers
array contains numbers that satisfy this condition.
10. Filtering based on Array of Conditions
Filtering based on multiple conditions.
const products = [
{ name: 'Phone', price: 500, category: 'Electronics' },
{ name: 'Shirt', price: 25, category: 'Clothing' },
{ name: 'Laptop', price: 1000, category: 'Electronics' },
{ name: 'Jeans', price: 50, category: 'Clothing' },
];
const expensiveElectronics = products.filter(product => {
return product.category === 'Electronics' && product.price > 500;
});
console.log(expensiveElectronics); // Output: [{ name: 'Laptop', price: 1000, category: 'Electronics' }]
In this case, we’re using a complex filter condition that checks both the product category and price to find expensive electronics.
These additional examples demonstrate the versatility of the filter
method in JavaScript for a wide range of filtering scenarios, from simple to complex conditions.