In this article, you will learn about the javascript Array built-in method Array.prototype.filter()
. How does this method work in javascript?
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.
array.filter(callback(element [, index [, array]]) [,thisParameter]);
This method takes 2 parameters:
Here are some examples of Array.prototype.filter() method:
//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 }
]
*/
filter()
method will skip empty array slotsI 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!
Comments