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.
- var requests = [{
- App: 'Adobe',
- Count: 10
- }, {
- App: 'Apple',
- Count: 12
- }, {
- App: 'Amazon',
- Count: 5
- }, {
- App: 'Microsoft',
- Count: 2
- }];
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.
- requests.find(function(item) {
- return item.App == "Apple"
- });
-
-
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.
- requests.filter(function(item) {
- return item.App == "Apple"
- });
-
-
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.
- requests.filter(function(item) {
- return item.App == "Apple"
- })[0];
-
-
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.