What is filter() used for ?
Sometimes you might want to do some changes on array so, to do that you need to use array methods in javascript. The filter() method is one of them. This method is used for filtering an array. It copies the given array and creates a new array using filtered elements from actual array. Suppose you have an array and only specific elements should be returned from the array. Let's see how to do that using filter().
How to use filter() method ?
Before use the method we are going to take a look at its syntax.
The syntax is
filter((element) => { /* … / } )
or
filter(function(element) { / … */ })
Alrigt let's do the first example. Suppose you have an array like [1, 2, 3, 4, 5, 6, 7, 8, 9] and want to get the only odd numbers.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const oddArr = arr.filter(element => element%2 == 0);
If you print out oddArr on console or page you are going to see a new array contains only odd numbers.
Attention !
filter() method doesn't change the original array.
filter() method creates a new array to fill with the selected elements by given condition.
We can also use filter() method on arrays includes string type element.
var format = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
const words = ['spray', '!limit#3', 'racing', '^b4n4n4*', '&basketball&', 'my$bird', 'animals', 'it_is_good_to_us', 'specialCars', 'sweet fruites']
const formattedArray = words.filter(w => w.length >= 6 && format.test(w) == false);
console.log(formattedArray) // [ 'racing', 'animals', 'specialCars' ]
The following example will create an array that doesn't include undefined items. To do that we are going to pass a function as parameter and see how to use without arrow function.
const arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: 'undefined' },
];
function catchUndefined(element) {
if (element.id !== 0 && Number.isFinite(element.id) && element.id > 0) {
return true;
} else {
return false;
}
}
const filteredArrById = arr.filter(catchUndefined);
console.log(filteredArrById);
Output
[ { id: 15 }, { id: 3 }, { id: 12.2 } ]
Another example will be around the numbers again. In this time we are going to find prime numbers from given array.
function isPrime(number) {
if (number > 1) {
for (let i = 2; i < number; i++) {
if (number % i != 0) {
continue;
} else {
return false;
}
}
} else {
return false;
}
return true;
}
const numbers = [3, 8, 2, 5, 4, 6, 11, 9, 7, 1, 24, 21, 17, -5, -7, -9]
const primeNumbers = numbers.filter(isPrime);
console.log(primeNumbers); // [ 3, 2, 5, 11, 7, 17 ]
After run the code above you are going to see the prime number list. Anyways, let's make an another instance using string type list.
const cars = ["BWM", "Audi", "Mercedes", "Volvo", "Subaru", "Volkswagen", "Hyundai", "Rolce Royce", "Bentley", "Nissan"];
query = "r"; // something else you want
const filteredByQuery = cars.filter(element => element.toLowerCase().trim().includes(query.toLowerCase().trim()));
console.log(filteredByQuery);
In the code above finds the proper elements according to given query. It searchs in the whole list and return item includes the query string.
So far so good !
You can make various examples to learn more and also look at these array methods map() and forEach().
Thank you so much for reading.
Top comments (0)