Javascript Find | JS Find | Javascript Array.Find()
Find an Item in JS Array? There are several ways to find an item in JS Array but using Javascript Array.Find() seems to be the most optimal way to achieve that.
Let’s see how does Javascript Find function works:
- JS Find function searches for the item in Javascript array and returns the first item that satisfies the search criteria.
- JS Filter function goes through all the items in JS Array and returns an array of all items that meets the search criteria.
var Array = ["john doe", "naomi kims", "dan jones", "ravi ks"]; Array.find(function(item){ return item === "john doe" });
Now, if you try to do same with Array.Filter() over Javascript Find() then you might have to do
var Array = ["john doe", "naomi kims", "dan jones", "ravi ks"]; Array.filter(function(item){ return item === "john doe" })[0];
So, we can avoid extra iteration as well as step to access first element of JS Array using Array.find().
But there might be scenarios when there is more than one record and you want all records to be returned. In that case use, JS Filter over JS Find.
Questions related to javascript find method are sometimes asked in Javascript Interview.
Here is an implementation of Array.find() in Javascript objects where it makes more sense.
Suppose we have to find an object where age is 20.
var Array = [{ name: " John Doe", age: 20 }, { name: "Raavi", age: 30 }, { name: "K Shay", age: 20 }];
Using Javascript Find(),
var Result = Array.find(function(item) { return item.age === 20 }) console.log(Result.name) // logs John Doe (remember first result)
Javascript Find() is supported across all browsers except IE. For such cases we need to write
the pollyfills of Array.Find() and JS Find() will work everywhere.
You can also use certain libraries that provide polyfills for such functions(Array.find()).