Introduction
The filter method is a powerhouse in JavaScript, allowing you to selectively extract elements from an array based on specific criteria. Let's dive in and demystify the filter method through practical examples and hands-on exercises.
Understanding the Filter Method
Similar to the map method, the filter method operates on each element of an array and returns a new array. The difference is that this time, the new array contains only the elements that respect specific criteria. Imagine you have an array of numbers, and you want to filter out only the negative numbers. Traditionally, you might use a loop, but the filter method offers a more elegant solution. See the following example:
const nums = [-2, 9, -18, 15, -7, -4, 6];
// Define a callback to check if a number is negative
const isNegative = (element) => {
const valid = element < 0; // element < 0 will return a boolean
// (true if the element is negative and false else)
return valid; // Then, we return true if the element is validated
// and false else.
// Note that we could have written directly:
// return element < 0; it would have been shorter
};
// Use the filter method with the callback
const negativeNumbers = nums.filter(isNegative);
console.log(negativeNumbers); // [-2, -18, -7, -4]
As seen above, the filter
method takes as a parameter a function which returns true
or false
if an element of the array will be kept in the new array or not. Here, we want to keep only the element < 0
, so the callback isNegative
will return true if an element is negative and then, the filter
method will add it to the new array. Else, the element is not added to the new array.
Now, let's practice
Consider the array of clothes below:
const stock = [
{ name: 'T-shirt', quantity: 50, size: 'M' },
{ name: 'Jeans', quantity: 30, size: 'L' },
{ name: 'Dress', quantity: 20, size: 'S' },
{ name: 'Jacket', quantity: 15, size: 'XL' },
{ name: 'Hoodie', quantity: 25, size: 'L' },
{ name: 'Shorts', quantity: 35, size: 'L' },
{ name: 'Skirt', quantity: 18, size: 'S' },
{ name: 'Sweater', quantity: 22, size: 'M' },
{ name: 'Pants', quantity: 28, size: 'L' },
{ name: 'Blouse', quantity: 14, size: 'M' },
];
Now imagine you are asked to get only the clothes with size 'L', try to write the code and let's correct it in the next part.
You did your best on the exercise, but would you like to check the correction to continue improving? Let's correct it :
const stock = [
{ name: 'T-shirt', quantity: 50, size: 'M' },
{ name: 'Jeans', quantity: 30, size: 'L' },
{ name: 'Dress', quantity: 20, size: 'S' },
{ name: 'Jacket', quantity: 15, size: 'XL' },
{ name: 'Hoodie', quantity: 25, size: 'L' },
{ name: 'Shorts', quantity: 35, size: 'L' },
{ name: 'Skirt', quantity: 18, size: 'S' },
{ name: 'Sweater', quantity: 22, size: 'M' },
{ name: 'Pants', quantity: 28, size: 'L' },
{ name: 'Blouse', quantity: 14, size: 'M' },
];
// This callback will check if an element size is 'L' and returns true
// if it is.
const checkSize = (element) => {
return element.size === 'L';
}
// Now we get a new array with the element which respect only
// the criteria defined in the callback
const stockL = stock.filter(checkSize)
console.log(stockL)
/*
[
{ name: 'Jeans', quantity: 30, size: 'L' },
{ name: 'Hoodie', quantity: 25, size: 'L' },
{ name: 'Shorts', quantity: 35, size: 'L' },
{ name: 'Pants', quantity: 28, size: 'L' },
]
*/
In complement
Like the map
method, the callback of the method filter
can take 3 parameters:
currentValue: the current element, exactly what we see until now
currentIndex: the index of the current element in the array
array: the array on which the operation is performed(the original array)
A last example of how this parameter can be useful ๐. Imagine you want to filter only the firsts/lasts x elements of an array, you can use the index to know where you are in the filtering. For instance, let's consider the array below again ๐:
const students = [
{ name: 'Alice', age: 22 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 20 },
{ name: 'David', age: 28 },
{ name: 'Emma', age: 23 },
{ name: 'Frank', age: 30 },
{ name: 'Grace', age: 21 },
{ name: 'Hank', age: 26 },
{ name: 'Ivy', age: 24 },
{ name: 'Jack', age: 29 },
{ name: 'Katie', age: 22 },
{ name: 'Liam', age: 27 },
{ name: 'Mia', age: 25 },
{ name: 'Noah', age: 23 },
{ name: 'Olivia', age: 28 },
{ name: 'Peter', age: 20 },
{ name: 'Quinn', age: 26 },
{ name: 'Rachel', age: 24 },
{ name: 'Sam', age: 29 },
{ name: 'Tom', age: 21 },
];
Now, you want to get the students who are less than 25 years old but you want this information only for the first 10 students in this array, how can you do it ?๐
You can simply apply the filter(less than 25 years old) only for the elements from index 0 to 9. Apply only the criterion 'less than 25' will be like:
const checkAge = (element, index, array) => {
return element.age < 25;
};
Then there is another criterion to respect: the first criterion is applying only for the 10 first elements of the array so let's complete our code:
const checkAge = (element, index, array) => {
// Check the age only for the 10 first students of the array
if (index < 10) {
return element.age < 25;
}
// if we are not on the 10 first elements, we don't need to check it
// and we don't want to add it to the new array so we return false
return false;
};
// Let's get now only the students who age are less than 25 years old
// in the 10 first elements:
const studentsFiltered = students.filter(checkAge);
console.log(studentsFiltered)
/*
[
{ name: 'Alice', age: 22 },
{ name: 'Charlie', age: 20 },
{ name: 'Emma', age: 23 },
{ name: 'Grace', age: 21 },
{ name: 'Ivy', age: 24 },
]
*/
And that's it for the filter
method. But before we part away, let me leave a last exercise. I will not correct it but you can set your answers and concerns on comments, I will try to answer it.
Consider this array:
const students = [
{ name: 'Alice', age: 22 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 20 },
{ name: 'David', age: 28 },
{ name: 'Emma', age: 23 },
{ name: 'Frank', age: 30 },
{ name: 'Grace', age: 21 },
{ name: 'Hank', age: 26 },
{ name: 'Ivy', age: 24 },
{ name: 'Jack', age: 29 },
{ name: 'Katie', age: 22 },
{ name: 'Liam', age: 27 },
{ name: 'Mia', age: 25 },
{ name: 'Noah', age: 23 },
{ name: 'Olivia', age: 28 },
{ name: 'Peter', age: 20 },
{ name: 'Quinn', age: 26 },
{ name: 'Rachel', age: 24 },
{ name: 'Sam', age: 29 },
{ name: 'Tom', age: 21 },
];
Your mission if you accept it is to retrieve a new array of all the students who are less than 25 years old and once, you should replace the attribute 'name' of each object with a new attribute 'firstname'.
map
and filter
methodGood coding ๐.
Join me in the next part of this series to implement our filter
method.