You've successfully subscribed to StackInk
Great! Next, complete checkout for full access to StackInk
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

How JavaScript Array Filter Method Works?

Array Filter is an inbuilt method in Javascript which is an efficient way to filter the elements you want to get from an array.

So, how does it work?


Simply put, JavaScript Array Filter method helps in creating a new filtered array containing elements of the original array when it satisfies a given condition set in the argument function.

Syntax

let newArray = array.filter(function(element) { return condition })


The filter method runs a callback for each element of the array. If the callback returns true for the condition, it will push that element to the new array, and if the condition is false, it will simply ignore the element.
It is important to note that the JavaScript filter() does not execute the function for array elements without any values and it won’t change the original array.

Examples


Filter through a simple array of numbers.

var numbers = [10,20,30,40,50,60,70,80,90,100]


From the numbers array, you want to get the element that is greater than or equal to 50.

var newNumbersArray = numbers.filter(function(element) { return element >= 50; });

//with Arrow Function
const newNumbersArray = numbers.filter(element => element >= 50; );

//output
// [50,60,70,80,90,100]


This also works on an array of objects:


Here we got an array of family members and the objective is to create new arrays, one representing adults and another with kids of the family.

//Family Array
const family = [
                {"name":"Mike", "age": 42}, 
                {"name":"Jude", "age": 39}, 
                {"name":"Thomas", "age": 9 }, 
                {"name":"Bill", "age": 7 }
              ];

//Filter the Adults of the Family
const Adults = family.filter(member => member.age >= 18; );

//Filter the Kids of the Family
const Kids = family.filter(member => member.age < 18; );

//Output Adults
[{"name":"Mike", "age": 42}, {"name":"Jude", "age": 39}]

//Output Kids
[{"name":"Thomas", "age": 9 }, {"name":"Bill", "age": 7 }]

Conclusion


In this article we learned how JavaScript filter() method creates a new array by filtering out all the elements that do not pass the test provided by the callback function.