How to search for an item in an array

The simple answer is array.find but there are more efficient ways.

Prince Shrestha
CodeX
2 min readOct 29, 2022

--

Photo by Mick Haupt on Unsplash

Before going into different ways of looking up an array, array.find or array.indexOf would be the preferred way, IF you are doing it once or twice.

Lookup using array.find

However, if you need to look up the same array multiple times, this becomes a bit costly as seen in this example we are iterating the same array 3 times.

This is where the Map comes in. No matter how many times you need to search an array, we will only iterate through the array once.

The basic idea is that you want to convert an array to a Map, which will work as a hash table. Since looking up a hash table is faster than an array, this will give your function a good boost.

Using a map, as you can see, the iteration only needs to happen once. We can quickly look up the items after that. We can also use the Map to check if some item exists in the array using the has method. If your function requires only checking if an item exists check out this article.

By using a map, you are using more memory for better performance, so as mentioned in the beginning, you will be better off using array.find if you are only looking up the array a few times. You can also use JS objects (which take less memory than maps) to make a hash map in a similar way.

--

--

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