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.
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 -
- Basic For Loop
- For...of
- For Each
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
Post a Comment