Find() vs. Filter() in JavaScript

This blog gives you the idea of when to use find() versus filter() in Javascript.

Introduction

 
When we handle an array in JavaScript, we may need to find a single item in the array collection. This may sound tedious, however, it shouldn't be too difficult if we use the appropriate methods.
 

Find and Filter

 
There are several alternatives to find the required values from the array, but here, I am going to use the find and filter methods in JavaScript. 
  1. var requests = [{  
  2.     App: 'Adobe',  
  3.     Count: 10  
  4. }, {  
  5.     App: 'Apple',  
  6.     Count: 12  
  7. }, {  
  8.     App: 'Amazon',  
  9.     Count: 5  
  10. }, {  
  11.     App: 'Microsoft',  
  12.     Count: 2  
  13. }];  
The find() method returns the first value that matches from the collection. Once it matches the value in findings, it will not check the remaining values in the array collection.
  1. requests.find(function(item) {  
  2.     return item.App == "Apple"  
  3. });  
  4.   
  5. //output: {App: "Apple", Count: 12}  
The filter() method returns the matched values in an array from the collection. It will check all values in the collection and return the matched values in an array.
  1. requests.filter(function(item) {  
  2.     return item.App == "Apple"  
  3. });  
  4.   
  5. //output: [ {App: "Apple", Count: 12} ]  
The find() method doesn’t work in IE <= 11. The filter() method works in all browsers, including IE9+. 
 
From the collection of filter() method result, you can get the first matched value using the below snippet. This method overcomes the IE combability issue of the find() method. 
  1. requests.filter(function(item) {  
  2.     return item.App == "Apple"  
  3. })[0];  
  4.   
  5. //output: {App: "Apple", Count: 12}  

Conclusion

 
The find() method is a better option to use across modern browsers, but if you care about the IE browser, use the filter() method.