;

Javascript Array - filter() Method


Tutorialsrack 11/09/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.filter().  How does this method work in javascript? 

Array.prototype.filter()

This Array.prototype.filter() method returns a new array with all the elements which pass the test that is implemented by the callback() function. The filter will shallow copy your object references into the new array

The filter() method iterates over each element of the array and passes each element to the callback function. If the element passes the text, then the callback function returns true, it includes the element in the return array. If no elements pass the test, an empty array will be returned.

Syntax
array.filter(callback(element [, index [, array]]) [,thisParameter]);

This method takes 2 parameters: 

  • callback: This parameter holds the function to be called for each element of the array. This function takes the mentioned parameters as below:
    • element: This parameter holds the current element of the array.
    • Index(Optional): This parameter holds the index of the current element within the array.
    • array(Optional): This parameter holds the reference to the original array.
  • thisParameter(Optional): This parameter holds the context to be passed as this is to be used while executing the callback function.

Here are some examples of Array.prototype.filter() method:

Examples
//Filter all the element in an array which is greater than 10
console.log([12, 5, 8, 130, 44].filter(x => x > 10));
// output => [12, 130, 44]


let cities = [
    {name: 'Los Angeles', population: 3792621},
    {name: 'New York', population: 8175133},
    {name: 'Chicago', population: 2695598},
    {name: 'Houston', population: 2099451},
    {name: 'Philadelphia', population: 1526006}
];

//filter all the cities where population is greater than 3000000
let metroCities = cities.filter(city => city.population > 3000000);
console.log(metroCities);
/*
             output
             
[
  { name: 'Los Angeles', population: 3792621 },
  { name: 'New York', population: 8175133 }
]

*/

I hope this article will help you to understandjavascript Array built-in method Array.prototype.filter()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags