Operator to verify collection membership in Javascript

How can I effectively perform collection membership checks in Javascript? I have a potentially large array of strings and I need to check if a given string is a member of the array.

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

For performance reasons, I would rather use js builtin, but if such a function does not exist, I will probably end up doing one of the following:

  • use an array to create an object with array elements as keys, and then use in
  • iterate over the elements of an array and a comparison element over an element
  • implement binary search

Any opinion? Or the best ideas?

thank

+5
source share
4 answers

As you will learn in this matter, almost every infrastructure has a function for this, some browsers even initially implement the function indexOf(not all of them, though).

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

HashSet .

+2

?

var inArray = function(array, value) {
    var i = array.length;

    while (i--) {
        if (array[i] == value) {
            return true;
        }
    }

    return false;

}

jsFiddle.

( , ), , .

+2

? ? , for in .

. , , . 2 .

0

, .

That way, you can very quickly run object membership tests and use an array when you need your objects to remain sorted.

This is the only way I found emulating a sorted dictionary type.

0
source

All Articles