filter: Creating a new array with elements that pass a test.
The filter()
method in JavaScript is a powerful tool for array manipulation. It iterates over each element of an existing array and creates a new array containing only the elements that satisfy a specific condition defined by a callback function.
Example 1: Filtering an array of numbers
// Define an array of numbers
const numbers = [10, 25, 8, 42, 15, 30];
// Filter out numbers greater than 20
const largerNumbers = numbers.filter(number => number > 20);
// Log the new array to the console
console.log(largerNumbers); // Output: [25, 42, 30]
Explanation
This code filters the numbers
array. The callback function number => number > 20
tests each element, and only the numbers greater than 20 are included in the largerNumbers
array.
Example 2: Filtering an array of objects
// Define an array of user objects
const users = [
{ name: 'Alice', isActive: true },
{ name: 'Bob', isActive: false },
{ name: 'Charlie', isActive: true }
];
// Filter for users who are active
const activeUsers = users.filter(user => user.isActive);
// Log the array of active users
console.log(activeUsers); // Output: [{ name: 'Alice', isActive: true }, { name: 'Charlie', isActive: true }]
Explanation
Here, we filter the users
array based on the isActive
property of each user object. The filter returns a new array containing only the user objects where isActive
is true
.
Example 3: Filtering out falsy values
// Define an array with mixed data types, including falsy values
const mixedArray = [0, 'Hello', '', false, 42, null, 'World', undefined];
// Filter out all falsy values (false, null, undefined, 0, '', NaN)
const truthyValues = mixedArray.filter(Boolean);
// Log the array of truthy values
console.log(truthyValues); // Output: ['Hello', 42, 'World']
Explanation
This example uses the Boolean
function as the callback. filter(Boolean)
is a concise way to remove all falsy values from an array, creating a new array with only the truthy values.
Example 4: Filtering based on string length
// Define an array of strings
const words = ['apple', 'banana', 'kiwi', 'strawberry', 'grape'];
// Filter for words with more than 5 characters
const longWords = words.filter(word => word.length > 5);
// Log the array of long words
console.log(longWords); // Output: ['banana', 'strawberry']
Explanation
This code filters the words
array. The condition word.length > 5
checks the length of each string, resulting in a new array, longWords
, that contains only the strings with more than five characters.
Example 5: Filtering with an index
// Define an array of numbers
const data = [10, 20, 30, 40, 50, 60];
// Filter for elements at an even index
const evenIndexElements = data.filter((element, index) => index % 2 === 0);
// Log the elements from even indices
console.log(evenIndexElements); // Output: [10, 30, 50]
Explanation
The filter
callback function can also accept the index of the element as a second argument. In this case, index % 2 === 0
filters for elements that are located at an even index in the original data
array.
Example 6: Filtering unique values
// Define an array with duplicate numbers
const duplicateNumbers = [1, 2, 3, 2, 4, 1, 5];
// Filter for unique values in the array
const uniqueNumbers = duplicateNumbers.filter((value, index, self) => {
return self.indexOf(value) === index;
});
// Log the array of unique numbers
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
Explanation
This example removes duplicate values from an array. It works by checking if the first occurrence of a value's index (self.indexOf(value)
) matches its current index, ensuring each unique value is included only once.
Example 7: Filtering based on a search term
// Define an array of product names
const products = ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Webcam'];
// Define a search query
const searchQuery = 'key';
// Filter products that include the search query (case-insensitive)
const filteredProducts = products.filter(product =>
product.toLowerCase().includes(searchQuery.toLowerCase())
);
// Log the filtered product names
console.log(filteredProducts); // Output: ['Keyboard']
Explanation
This demonstrates a common use case: a search filter. It converts both the product name and the search query to lower case for a case-insensitive comparison, returning a new array of products that contain the search term.