Filter () method explained: JS (hashnode.dev)

Translator: Mancuoj

Note: The semantics of filter itself are filters, so the function of the method can be understood as filtering out elements that fail the test.

The filter() method creates a new array containing all the elements from the old array that passed a test, provided as a function.

Let’s look at the syntax:

let new = array.filter((v, i, a) = > {
    // If the condition is met, the element is returned to new
    // Skip the element if the condition is not met
});

// new - New array
// array - The filtered array
// v - The current value being processed, i.e. Value
// I - the index of the current value being processed
// a - primitive array, i.e. Array
Copy the code

The filter() method can be thought of as a loop designed to filter certain values in an array.

Look at the following example:

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 =,14,16 [12]
Copy the code

This code tests all the values in the NUMS array, and only even values are accepted and pushed into the evenNums array.

Although it is possible to write it this way, there is an easier way to achieve the same result.

We override the previous function using the filter() method:

let nums = [11.12.13.14.15.16];
let evenNums = nums.filter(value= > value % 2= = =0); 
/ / evenNums =,14,16 [12]
Copy the code

Look, there’s no loop.

We can create the same array with a nice, clean function. Because we only use the value in the array, we simply pass the value to the filter() method.

Now let’s look at a more complex example — an array of objects. Here’s the data we need to use:

let data = [ 
    { 
        country: 'Netherlands'.population: 17122267}, {country: 'Germany' , 
        population: 83694772}, {country: 'United Kingdom'.population: 67767045}, {country: 'Belgium' , 
        population: 11572813,}];Copy the code

So now what?

We want to create a new array that contains only countries with a population of less than 50 million. We need to test the data and return the correct data for those countries with a population of less than 50 million.

let smallCountries = data.filter(v= > v.population > 50000000);
Copy the code

All it takes is one line of code to ensure that countries with small populations enter our new array.

Even though our data is more complex, the filtering process is relatively unchanged.

After running our filter function, we get this:

// smallCountries = [
// {country: "Netherlands", population: 17122267},
// {country: "Belgium", population: 11572813},
// ];
Copy the code

That’s all, thank you for reading!