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:
in
Any opinion? Or better ideas?
Thanks
"in" Operator A collection such as a list, set, string, or tuple can be checked for membership by using the in operator.
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").
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With