Share with   

Filter array object list using JavaScript

Using JavaScript language, we are filtering the array list items for search or sorting the list using some JavaScript functions.


JavaScript Array Filters

 

Using JavaScript language, we are filtering the array list items for search or sorting the list using some javascript functions.

The most common task in programming is filtering and searching the list of available items in the array.

We have city multiple objects in array list contains name and population.

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

 

Ex. To find the cities whose population greater than 3 lakhs.

 

Solution 1

Using for loop and if condition we can iterate the array and by applying if condition, we can push the finding value in a new array.

let bigCities = [];
for (let i = 0; i < cities.length; i++) {
    if (cities[i].population > 3000000) {
        bigCities.push(cities[i]);
    }
}
console.log(bigCities);

Output:
[
  { name: 'Los Angeles', population: 3792621 },
  { name: 'New York', population: 8175133 }
]

 

Solution 2

Using built-in filter() in JavaScript ES5

let bigCities = cities.filter(function (e) {
    return e.population > 3000000;
});
console.log(bigCities);

Output:
[
  { name: 'Los Angeles', population: 3792621 },
  { name: 'New York', population: 8175133 }
]

 

Solution 3

Using built-in filter() in JavaScript ES6 it is very simple in one line using the arrow (=>) method.

let bigCities = cities.filter(city => city.population > 3000000);
console.log(bigCities);

Output:
[
  { name: 'Los Angeles', population: 3792621 },
  { name: 'New York', population: 8175133 }
]

 

JavaScript filter() Syntax:

arrayObject.filter(callback, contextObject);

The filter() method creates a new array with all the elements that pass the test implemented by the callback() function.

Thank you for watching the article.

If you like, please like and share with your developer friends.

Author Image
Guest User

0 Comments