Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fastest way to detect if a value is in a group of values in Javascript

I have a group of strings in Javascript and I need to write a function that detects if another specific string belongs to this group or not.

What is the fastest way to achieve this? Is it alright to put the group of values into an array, and then write a function that searches through the array?

I think if I keep the values sorted and do a binary search, it should work fast enough. Or is there some other smart way of doing this, which can work faster?

like image 943
Gabriel Avatar asked Nov 21 '08 08:11

Gabriel


People also ask

How do you check if a value is within a range in JavaScript?

const inRange = (num, num1, num2) => Math. min(num1, num2) <= num && Math. max(num1, num2) >= num; Could be like this if you want to make inRange inclusive and not depend on order of range numbers (num1, num2).

How do you check if an array contains a specific value in JavaScript?

JavaScript Array includes()The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.

How do you find the range of an IF condition?

To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range.

How do you check if a value is in a string?

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string. In all other cases the variable isn't a string. Copied!


2 Answers

Use a hash table, and do this:

// Initialise the set

mySet = {};

// Add to the set

mySet["some string value"] = true;

...

// Test if a value is in the set:

if (testValue in mySet) {
     alert(testValue + " is in the set");
} else {
     alert(testValue + " is not in the set");
}
like image 154
Simon Howard Avatar answered Sep 20 '22 11:09

Simon Howard


You can use an object like so:

// prepare a mock-up object
setOfValues = {};
for (var i = 0; i < 100; i++)
  setOfValues["example value " + i] = true;

// check for existence
if (setOfValues["example value 99"]);   // true
if (setOfValues["example value 101"]);  // undefined, essentially: false

This takes advantage of the fact that objects are implemented as associative arrays. How fast that is depends on your data and the JavaScript engine implementation, but you can do some performance testing easily to compare against other variants of doing it.

If a value can occur more than once in your set and the "how often" is important to you, you can also use an incrementing number in place of the boolean I used for my example.

like image 43
Tomalak Avatar answered Sep 19 '22 11:09

Tomalak