Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to find if a string is in an array

Tags:

People also ask

How do you check if a string is present in array of strings in C?

int len = sizeof(x)/sizeof(x[0]); You have to iterate through x and do strcmp on each element of array x, to check if s is the same as one of the elements of x.

How do you check if a string is present in an array Java?

contains() Method: List contains() method in Java is used for checking if the specified element exists in the given list or not.

How do you check if a string is in an array C++?

Simply use this function. std::find(std::begin(tab), std::end(tab), n); will return an iterator to the element if it was found, the end iterator otherwise. Checking for equality with the end iterator will tell you if the element was found in the array.

How do you check if an element is in an array?

The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.


In Ruby, finding out if a string is in an array (.include? x) is very slow. If you change that array into a set, then BAM, lightning fast lookups.

In JavaScript, where there are no sets, array lookups (.indexOf(x) >= 0) are also very slow, however I need to be doing 10,000s of these lookups in a script.

My Ruby version (with sets) runs in 0.125 seconds, my JavaScript version (in NodeJS) takes 29!

Is there a any set library or better way to perform array lookups that could get the Javascript speed near the Ruby?

Edit: Changed "objects" to "strings" to clear up any confusion