How to filter an array in JavaScript
Published Sep 1 2022
The filter() method in JavaScript iterates through an array, invoking a predicate function upon each element and returning a new array that contains only those elements for which this function returned a truthy value. We can think of the predicate as a condition that the element must pass to be included in the new array.
Some examples of when the filter() method is helpful include building an array that contains only truthy values, even numbers or values that are not in another array.
Simple JavaScript array filter examples
Code Playground
Filtering an array of objects
It is a common requirement to filter an array of objects based on a property of the object having a particular value. The filter() method can be used in exactly the same way as it was for the more simple arrays above.
Filtering an array of objects examples
Code Playground
So, just as we use a coffee filter to remove unwanted sediment from a combination of hot water and ground coffee, the JavaScript filter() method allows us to create a new array from an existing array with the unwanted elements removed.
Far out, right!?