The Array Filter() Method for Beginners

Daniel Kim
3 min readMar 31, 2021

Very often, one will need to return certain elements from an array. This can typically be done through a for loop; however, in ECMAScript5, which was released in 2009 and was JavaScript’s first major revision, we gained the ability to filter through an array.

The filter() method is a built-in array method in Javascript that can return a new array that consists of elements from a given array that pass a test or satisfy a condition set by an argument.

Below is an example of using the for loop. As you can see, we are trying to populate our “bigWords” array with words that have more than 5 letters from our given “words” array.

This console.log will log the following output. We have successfully filled our “bigWords” array with the three words that have more than 5 letters from the given “words” array.

Using the same given array, we will now use the array filter() method and check our output.

Here is our output from the console.log.

This console.log shows that we were able to get the exact same output with the array filter() method as when using a for loop but with way shorter and cleaner looking code.

The syntax for the array filter() method is as follows.

As demonstrated in the picture above, the array filter() method accepts five different parameters. These parameters are made up of the following:

  • callback: contains the function that is used to test each element of the array.
  • currentValue: holds the value of the current element being processed.
  • index: holds the index of the currentValue and is optional.
  • array: holds the array object the currentValue belongs to and is optional.
  • thisValue: the value to be used as this when executing the callback and is optional.

Here is one more example of using the array filter() method. We are given an array of objects that has four different cats and want to filter for the female cats.

Our output from the console.log will be the following.

The array filter() method is an extremely useful tool that every programmer will use and become familiar with throughout their coding journey. I hope this little beginner tutorial can be helpful for those of you starting down this path.

Thank you for reading!

References

--

--