Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator to test for collection membership in Javascript

how could I efficiently do collection membership checks in Javascript? I have a potentially large array of strings and I need to verify if a given string is a member of the array.

Initially I thought that the in operator could help, but after reading the docs on Mozilla Developer Network I discovered that its purpose is different. In Javascript it checks if the specified property is in the specified object.

For performance related reasons I'd prefer to use a js builtin, but if a such function doesn't exist I'll probably end to do one of the following:

  1. use the array to create an object having array elements as keys and then use in
  2. iterate over array elements and do the comparison item by item
  3. implement a binary search

Any opinion? Or better ideas?

Thanks

like image 460
Paolo Avatar asked Mar 08 '11 11:03

Paolo


People also ask

Which operator can you use to test for item membership in a collection?

"in" Operator A collection such as a list, set, string, or tuple can be checked for membership by using the in operator.

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").

What is in operator in JavaScript?

The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists.

Can we use collection in JavaScript?

In JavaScript, there are two types of keyed collections: Map and Set . Both Map s and Set s in JavaScript can have a single value attributed to a single key, though you could hack it by attributing a List as a value, containing multiple elements.


1 Answers

As you'll find out in this question, pretty much every framework has a function for that, some browsers even natively implement an indexOf function (not all of them though).

It seems that they all do it by iterating the array, some using the other direction (starting from the end) because it seems to be faster. For sublinear algorithms, you'll probably need to implement some kind of a hash set with binary search on keys.

Example of a HashSet implentation can be found here.

like image 158
Tomas Vana Avatar answered Oct 09 '22 14:10

Tomas Vana