Filter Array in Javascript

    Apr 14, 2020       by Pankaj Kumar
filter-array-method-in-javascript.jpg

Javascript comes with a bulk set of methods to perform operations on Array and strings. filter() is one of the very common functions which frequently used to filter data.

 

In this article, We will see the different scenarios with filter() to perform all types of filter tasks with the filter().

 

Filter() function Syntax

 

var newArray = array.filter(function(item) {

  return condition;

});

 

The argument item is the current element of the array on which condition applies and if it matches then pushed to the new array.

filter() creates a new array with filtered elements that lie under specific conditions.

Simple Array Filter Example:

 

 
var numbers = [1, 5, 7, 9, 11];
 
var lucky = numbers.filter(function(number) {
return number > 6;
});
 
// Output: [ 7, 9, 11 ]
 

 

 

Filtering an array of objects

An array of objects can also be filtered very easily with the filter().

 

 
var fruits = [
  {name: "Mango", count: 20},
  {name: "Orange", count: 12},
  {name: "Banana", count: 32},
  {name: "Apple", count: 56},
];
 
var availableFruits = fruits.filter(function(fruit) {
  return fruit.count >20;
});
// Output: [{name: "Banana", count: 32},{name: "Apple", count: 56}]
 

 

With multiple conditions

 

 
var fruits = [
  {name: "Mango", count: 20,quality:"good"},
  {name: "Orange", count: 12,quality:"average"},
  {name: "Banana", count: 32,quality:"bad"},
  {name: "Apple", count: 56, quality:"good"},
];
 
var availableFruits = fruits.filter(function(fruit) {
  return fruit.count >20 && fruit.quality==='good';
});
// Output: [{name: "Apple", count: 56, quality: "good"}]
 

 

Follow previously posted article on this platform, If you want to know more about the other higher-order function of javascript(map, reduce, forEach)

Conclusion

Working with filter() is very easy and it makes the filter task on Array very easy.

 

Click here to find Sample Applications on different javascript frameworks.

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thank You!


WHAT'S NEW

Find other similar Articles here: