3 Ways to Search in Array - JS

You will often need to search contents which are stored in an Array.

How do you do that?




1. Using Array.find

Array.find method will return a single match from the array based on your query. It stops searching as soon as the first match is found. So, it returns the first result only.


const arr = [9, 10, 5, 1, 0, 3, 4, 8, 12]

const res = arr.find(el => el > 5)

console.log(res)

// 9


2. Using Array.filter

This method works just how find works. The difference is, it returns all the matches as an array.


const ages = [32331640]

const res = ages.filter(el => el > 30)

console.log(res)
// [32, 33, 40]


3. Using For Loop

Well, this is not the best method but it is possible to write a searching function with for loops. You may use -


  1. Basic For Loop
  2. For...of
  3. For Each

You can also try using other loops like For...in, While etc.


See an example and discussion about it: https://stackoverflow.com/questions/50843682/for-loop-with-break-vs-find-in-javascript


⚠️ But, remember, these are not recommended ways to search in an array. These will be effectively slower and the performance will not be as good as the built-in functions.


Conclusion 

I hope, it was helpful for you as a quick review.

👇 Let me know what you think in comments. Thanks for reading! 




Comments