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"
});
//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.
requests.filter(function(item) {
return item.App == "Apple"
});
//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.
requests.filter(function(item) {
return item.App == "Apple"
})[0];
//output: {App: "Apple", Count: 12}
Let us see the Differences:
find() | filter() |
The find() method is used to find all the descendant elements of the selected element. | The filter() method is used to filter all the elements |
The find() method finds the element in the DOM tree by traversing through the root to the leaf. | The filter() method returns the element that matches and removes the element that does not match. |
The find() method search through all the child elements only. | The filter() method search through all the elements |
It does not execute the function for empty elements. | The filter() method does not change the original array. |
It does not change the original array. | The filter() method does not execute the function for empty elements. |
Its syntax is: array.find(function(value, Index, array),thisValue) | Its syntax is: array.filter(function(value, Index, array), thisValue) |
This method returns undefined if no elements are found. | In filter() method a value is passed to the function as its this value |
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.