DEV Community

Cover image for Filter Your JavaScript Array Elements Based on a Condition With .filter()
Todd Carlson
Todd Carlson

Posted on

Filter Your JavaScript Array Elements Based on a Condition With .filter()

One of my favorite things about the JavaScript language is that it provides many useful array methods. One such array method that I find myself using over and over is .filter(). In a nutshell, .filter() allows you to pass in a test function which will return a new array consisting of only the elements from the original array that meet a specific condition.

For example, let's say that we have an array of numbers, and that we would like to create a new array consisting of only the even numbers from our original array.
Alt Text
You could write out a whole function involving a for loop, some conditional logic, and pushing elements into a new array. However, I prefer to use .filter() because there is less code to write, and the syntax is much cleaner.

To get back a new array of only the even numbers from our original array you simply write:
Alt Text
And that's all there is to it. You can also use .filter() on an array of objects, to return a new array of objects containing only those objects that meet the condition that you provide.

There are many different array methods available in the JavaScript language, but .filter() is one I guarantee you will use over and over again.

Thanks for reading, and happy coding!

Oldest comments (0)