How to check if an item exists in an array

Are there better ways than array.findIndex?

Prince Shrestha
CodeX
2 min readOct 29, 2022

--

Photo by Markus Winkler on Unsplash

Say you had an array of numbers and you wanted to check if a certain number exists in that array. You can use indexOf (if it’s an array of primitive types) or findIndex, and check if the result is -1 (false) or the index of item (true).

Now, let's say we need to check if 100 fruits exist in that array. We would be running .findIndex 100 times (running 100 iterations on the same array). In such a case, we should use Sets.

Take note that by creating a set, you will be using more memory so this method would not be appropriate if you are only looking up the array a few times.

Using sets, we can only know if the item exists in the array or not. What if we needed the item that we look up? For that, we would need to use Maps or Objects, for which you can check out this article.

--

--

Prince Shrestha
CodeX

wants to help make your JS journey much smoother. Support me by following me or buying me a small picollo for the mornings https://ko-fi.com/shresthaprince