Tuesday, 12 October 2021

Javascript filter() method

 Hi,

Here we are going to learn how to filter the objects in an array with filter() method.

  • The filter() method creates an array filled with all array elements that pass a test (provided by a function).
  • filter() does not execute the function for empty array elements.
  • filter() does not change the original array.


Example 1:

Prepare an array with words which has a length greater than 3 from the following arrray.

let words = ['elephant', 'cat', 'dog', 'tiger', 'lion'];

Without Filter method:

let wordsarray = [];

for (let i = 0; i < words.length; i++) {

    if (words[i].length> 3) {

        wordsarray.push(words[i]);

    }

}

console.log(wordsarray);

Output:

["elephant", "tiger", "lion"]


With filter method:

let wordsarray = [];

wordsarray  = words.filter(word => word.length > 3);

console.log(wordsarray );

Output:

["elephant", "tiger", "lion"]


Example 2:

 Find the cities whose population is greater than 30000 from the following array.

let cities = [

    {name: 'Hyderabad', population: 40000},

    {name: 'Karnool', population: 36000},

    {name: 'Kadapa', population: 37000},

    {name: 'Tirupati', population: 29000}  

];

Without Filter method:

let bigCities = [];

for (let i = 0; i < cities.length; i++) {

    if (cities[i].population > 30000) {

        bigCities.push(cities[i]);

    }

}

console.log(bigCities);

Output:

[

 { name: "Hyderabad", population: 40000 },

 { name: "Karnool", population: 36000 },

 { name: "Kadapa", population: 37000 }

]

With filter method:

let bigCities = cities.filter(e => {

    return e.population > 30000;

});

console.log(bigCities);

Output:

[

 { name: "Hyderabad", population: 40000 },

 { name: "Karnool", population: 36000 },

 { name: "Kadapa", population: 37000 }

]


Reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter




What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...