The filter()
method creates a new array filled with all the elements of the old array that pass a certain test, provided as a function.
Let's take a look at the syntax:-
let new = array.filter((v, i, a) => {
// return element to new if condition are met
// skip element if conditions are not met
});
// new - the array that is returned
// array - the array to run the filter function on
// v - the current value being processes
// i - the current index of the value being processed
// a - the original array
The filter()
method can be thought as of a loop, that is specifically for filtering in/out certain values from an array. See the example below:-
let nums = [11, 12, 13, 14, 15, 16];
let evenNums = [];
for(var i = 0; i < nums.length; i++) {
if (nums[i] % 2 === 0) evenNums.push(nums[i]);
}
// evenNums = [12,14,16]
This code tests all of the values in the nums array. Only the even values are accepted and pushed onto the evenNums array. yes, it works, but there is an easier way to achieve the same result.
Rewriting the previous function using the filter()
method.
let nums = [11,12,13,14,15,16];
let evenNums = nums.filter(value => value % 2 === 0);
// evenNums = [12,14,16]
Just see. Without any loop.
And using the arrow function we have a nice and clean function to create the same array. Because we only use the value, we only pass that to the filter()
method.
Now we will see a more complex example that utilizes an array of object. Below is the data we will be using for our example.
let data = [
{
country: 'Netherlands',
population: 17122267, 1,
},
{
country: 'Germany' ,
population: 83694772,
},
{
country: 'United Kingdom',
population: 67767045,
},
{
country: 'Belgium' ,
population: 11572813,
}
];
So now what ?
We want to create a new array with only with the countries that have a population smaller than 50million. To do this, all we have to do is test our data and return true id data.population is smaller than 50,000,000.
let smallCountries = data.filter(v => v.population > 50000000);
Just this one line code ensuers that only the smaller countries make it our new array. Even though our data is more complex the process to filter it remains relatively unchanges. Aftfer running our filter function, we're left with this:
// smallCountries = [
// {country: "Netherlands", population: 17122267},
// {country: "Belgium", population: 11572813},
// ];
I'm Done! Thanks For Reading.
If you find it useful plz show some love and comment.
First Seen Here