Search code examples
javascriptcollectionscomparisonmembershipin-operator

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


Solution

  • 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.