When working with an array in JavaScript, we may need to locate a single item within the collection. This may appear tiresome, but if we apply the right methods/procedures/techniques, it shouldn't be too tough.
There are various ways to extract the needed values from an array, but we'll utilize JavaScript's .find() and .filter() methods here.
A coding example
We have an array of appsArray:
const appsArray = [{
Name: 'Canva',
ID: 10
}, {
Name: 'VS Code',
ID: 12
}, {
Name: 'Github',
ID: 52
}, {
Name: 'Adobe',
ID: 23
}];
We need an app with an ID of 12
find()
The find() method returns the first value from the collection that matches. It will not examine the other values in the array collection after it matches the value in findings.
appsArray.find(function(item) {
return item.ID === 12
});
//output: {Name: "VS Code", ID: 12}
filter()
The filter() method returns the collection's matched values as an array. It will verify all of the values in the collection and return an array of the matching values.
appsArray.filter(function(item) {
return item.ID === 12
});
//output: [ {Name: "VS Code", ID: 12} ]
In Internet Explorer 11, the find() method does not work. All browsers, including Internet Explorer 9+, support the filter() method.
Using the snippet below, you can obtain the first matched value from the collection of filter() method results. This solution solves the find() method's IE compatibility problem.
appsArray.filter(function(item) {
return item.ID === 12
})[0];
//output: {Name: "VS Code", ID: 12}
Conclusion
The find() technique is preferable for newer browsers, but if you care about Internet Explorer, you should use the filter() method.
.find() returns the first matching element, while .filter() returns an array of all matching elements.
Hope you found this article useful, if you did, shoot me a comment to let me know. If you think I did something wrong, please also let me know in the comments.
Happy coding.