Javascript filter() method: index, multiple conditions, remove duplicates, map
The JavaScript filter()
function is an essential method that allows you to get a new array from an existing array, filtered by only the elements that match certain conditions.
In this article, I'll show you how to use the filter()
function, including the index
parameter, using multiple conditions, and removing duplicates,
We will learn how to use the includes()
method and how it differs from the map()
and find()
methods.
1. Filter() function basics and index parameter
In JavaScript, the filter()
method is a method that extracts only the elements of an array that satisfy certain conditions and creates a new array.
The basic syntax is shown below.
array.filter(callback(element[, index[, array]])[, thisArg])
The filter()
method takes a callback function as a parameter, which is executed for each element in the array and returns a value of either true
or false
.
At this point, the callback function returns a new array consisting only of elements that return a value of true
.
Let's see how to use this function with a simple example.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
In our example, we received the arrow function number => number % 2 === 0
as a callback function.
And when we applied it, we can see that it returned a new array containing only 2
, 4
, which returns the value true
.
Like the forEach() and map() functions, the callback function can take two optional parameters.
In the example below, these are the 2nd and 3rd parameters, named index
and array
respectively, to access the index of the current element and the array itself.
You are free to name the parameters whatever you like.
const numbers = [10, 20, 30, 40, 50];
numbers.filter((number, index, array) => {
return index % 2 === 0
});
// Output: [10, 30, 50]
The filter()
function in the example uses the index of the current element as the index
parameter and defines a condition that only elements at positions 0
, 2
, and 4
are returned.
are returned.
2. Using multiple conditions
There are two ways to use multiple conditions.
The first is to use the relational operator &&
to set multiple conditions.
Next, we'll check for two conditions: a number that is a multiple of 3
and greater than 5
.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const filteredNumbers = numbers.filter(number => number % 3 === 0 && number > 5);
console.log(filteredNumbers); // Output: [6, 9]
The second is to use multiple filter
functions in a chain, like this
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const filteredNumbers = numbers.filter(number => number % 3 === 0).filter(number => number > 5);
console.log(filteredNumbers); // Output: [6, 9]
3. Remove duplicates with filter()
Using the filter()
function is an easy way to remove duplicate elements from an array.
Let's start with the sample code.
const array = [1, 2, 3, 2, 4, 3, 5, 1];
const uniqueArray = array.filter((element, index, array) => {
return array.indexOf(element) === index;
});
console.log(uniqueArray);
// Output: [1, 2, 3, 4, 5]
The callback function in the example above uses both the index
and array
parameters we saw in Section 1 to construct the algorithm.
The
Array.indexOf(element)
method returns the smallest index in the array that matches the valueelement
. (If it doesn't exist, it returns-1
).
If the current element is the only value in the array, the return value of the array.indexOf()
method is equal to the current element's index
value.
Conversely, if the return value of the callback function is false
, it means that there is more than one value, which will be filtered out by the callback function.
4. Defining a callback function with includes()
The String.includes(string)
method returns whether the value string
is included in the string.
Used in conjunction with the filter()
method, this is a great way to select only those elements in an array of strings that contain a particular substring.
Let's look at a simple example.
const subjects = ["Basic English", "Basic Chinese", "Intermediate Japanese", "Intermediate French", "Basic Chemistry"]
const basics = subjects.filter(subject => subject.includes("Basic"))
console.log(basics)
// Output: [ 'Basic English', 'Basic Chinese', 'Basic Chemistry' ]
In the above example, the includes
method returns a value of true
only for subjects that contain the string "Basic"
.
As a result, out of the five courses, we were able to filter only those that contained the string "Basic"
.
As you can see, the two methods can be used together to achieve synergy in many cases.
5. difference from map()
The filter()
function, along with forEach(), map(), and reduce(), are array methods that can be used with
These are the array methods that you can use. Each method has its own functionality, so it's important to know the difference and use them well.
For a more detailed explanation of each method, see their respective posts.
forEach()
: Traverses all elements of the array and executes the given callback function.map()
: Applies the callback function to each element and returns a new array with the return value of the callback function.reduce()
: Applies a function that combines the previous value with the current value, summing the values in the array into a single value.
The main difference with the map()
function is the callback function and the array it returns.
The callback function of the map()
function returns a new element, and these values make up the new array, so the length of the array is always the same.
The callback function of the filter()
function returns a reference that determines which elements will be included in the new array.
The length of the new array will always be less than or equal to the old array, and the element values will not change.
6. difference from find()
The Array.find(condition)
method finds an element in the array that matches the condition defined in the callback function condition
and returns the value.
If there are multiple elements, it returns only the element with the lowest index, or undefined
if not found.
The callback function has the same form as the filter()
function.
const result = array.find(callback((element, index, array) => {
// Condition logic
// Return true or false
}))
Let's look at a usage example.
const numbers = [1, 2, 3, 4, 5, 6];
const firstEvenNumber = numbers.find((number) => {
return number % 2 === 0;
});
console.log(firstEvenNumber);
// Output: 2
It returned the value 2
, which is the value of the smallest index that matches the condition.
As you can see, the find()
method is the same as the filter()
method in that it finds a value that matches the condition, but unlike the filter()
method, it returns only one value.
7. Conclusion
We've seen how the filter
function can be used to filter only those elements in a given array that match a condition.
While this method is powerful when used alone, there are many more possibilities when used in conjunction with other array methods,
It's worth exploring ways to use it in conjunction with other functions and methods.
