5

If I have a whitelist of strings that I want to check everything the user inputs into my javascript program, what's the most efficient way to do that? I could just have an array and loop through it until a match has been found but that's O(N). Is there an yway to do it that's better and doesn't involve any sort of key value lookup, just checking to see if that value exists?

EDIT: I guess what I'm looking for is the equivalent of a set in C++ where I can just check to see if a value I'm given already exists in the set.

3

3 Answers 3

1

Just make it a simple js object instead of an array.

var whitelist = {
  "string1":true,
  "string2":true
}

and then you can just check if(whitelist[str]) to check if its available.

Or use if(str in whitelist).

I expect that the first will have slightly better performance (I haven't verified that), but the second is more readable and makes the purpose clear. So its your choice of which is a better fit.

2
  • FWIW, I'm fairly sure the first check is faster in most engines.
    – forivall
    Commented Mar 21, 2013 at 18:55
  • 1
    I agree, which is why I put it first, but the second is more readable. Edited to reflect this. Commented Mar 21, 2013 at 18:57
1

Sort the array, use binary search for the look-ups.

Or

Create an object where the key is the item and use the hash look-up whitelist[value] != undefined

1

I think you'll find that key-value lookup is almost identical in performance to some kind of set implementation without values. (Many standard libraries actually just implement a set using a map)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.