A look at filter() vs. find() array methods in JavaScript
JavaScript provides two powerful and super useful array methods named filter() and find() methods.
Get TANVIR AHMED’s stories in your inbox
Join Medium for free to get updates from this writer.
First, let’s get to know a little about both of these array methods before diving deep into the actual code. Suppose, we want to have a checkpoint and take array elements only according to this checkpoint. We don’t want to take any array element that doesn’t pass the condition(provided by a function). Then, we can use the filter() array method for this purpose. But if we only want to have the first array element that matches our given condition(provided by a function) then we can make use of the find() method that JavaScript provides for us.
Let’s understand this with a coding example
Here, we can see an array of objects, where each of these objects has a color property.
Now, we want to have the product which is red colored.
Getting all red colored products inside the array using filter() method
Code Output
Above, we can see the filter() method returns two red colored products inside a new array.
Getting the first red colored product inside the array using find() method
Code Output
Above, find() method returns the value of the first red colored product found in the provided array.
Whatever condition you set inside the function, any array element that fulfills that condition will make the filter() method return the full element inside a new array. If no element matches the condition, then the method will return an empty array. Whereas, the find() method will directly return you the value of the matching array element, but not inside any array. The find() method returns the first element that matches the condition, even if there are more elements that might match the condition. But if no element is matched by the condition, then the find() method will return you undefined. One more thing to remember, both filter() and find() method do not change the original array.









