Just like the map method, JavaScript provides us with another very helpful method, filter. And as the name suggests we can use it to filter out values from an array.

Let’s start by looking at how Mozilla Developer Network describes the filter method:

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

  • Of course we will need an array, to run the filter method on
  • We have to supply a function to this method
  • This function is called on every element in the array
  • Elements are filtered out depending on the test in the function
  • And the output is a new array

Now that the definition is out of our way, let’s look at an example. We have an array of ten numbers and we want to extract all even numbers from this array into a new array.

Here is how we achieve this using a For Loop:

What’s going on here? let’s see :

  • Create a new array
  • Keep track of each element
  • Check if each element is even
  • If yes push element into the new array

This can also be achieved using a library like Lodash:

And now using JavaScript’s filter method

Important notes about the filter method

  1. The filter method is defined on Array.prototype, so we call it on any array, and it accepts a callback as its first argument.
  2. In the above code we are passing just one argument to the function, that is the current number. But we can pass a total of three arguments to this function:
    • The current item in the array
    • The array index of the current item
    • The entire array you called map on
  3. The return statement. We have to make sure that the return statement returns a boolean value. If we forget the return statement, the function will return undefined and filter will assume it as false and we will get an empty array. And if the return statement does not return a boolean value, JavaScript logic will be applied to figure out if it’s true or false, which always results in hidden bugs.

We can also use ES6(ES2015) ‘fat arrow’ :

And now a look at a more practical example, suppose we call an API that returns an array of objects. Something like this :

Now, we decide that we just want to display users above the age of 18. Here is how we will achieve this:

Note, in case you are using Angular, it would be a good idea to use a pipe to achieve this result.

That’s about it for this post.