Javascript Concepts

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.
You might find Javascript developers using JS Filter method to find an item in an array but it has a major drawback.
  • JS Filter function goes through all the items in JS Array and returns an array of all items that meets the search criteria. 
So, using JS Find Function or Javascript Array.Find(), we can avoid that and finish our search as soon as we hit the first target.
 
Now, let’s focus on how can we implement Array.Find() or JS Find for any given array:
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()).

Read my interview experience on Walmart, Amazon, Flipkart, MS, Paytm, MMT, OYO, Intuit, etc.
Links:
 
 

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to receive helpful content for your next Front End Interview. No Junk. No Spam.

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

FE / JS will use the information you provide on this form to be in touch with you and to provide updates and marketing.