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

2020-01-29 08:07发布

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?

9条回答
地球回转人心会变
2楼-- · 2020-01-29 08:34

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.

查看更多
【Aperson】
3楼-- · 2020-01-29 08:34

A possible way, particularly efficient if the set is immutable, but is still usable with a variable set:

var haystack = "monday tuesday wednesday thursday friday saturday sunday";
var needle = "Friday";
if (haystack.indexOf(needle.toLowerCase()) >= 0) alert("Found!");

Of course, you might need to change the separator depending on the strings you have to put there...

A more robust variant can include bounds to ensure neither "day wed" nor "day" can match positively:

var haystack = "!monday!tuesday!wednesday!thursday!friday!saturday!sunday!";
var needle = "Friday";
if (haystack.indexOf('!' + needle.toLowerCase() + '!') >= 0) alert("Found!");

Might be not needed if the input is sure (eg. out of database, etc.).

I used that in a Greasemonkey script, with the advantage of using the haystack directly out of GM's storage.

查看更多
劳资没心,怎么记你
4楼-- · 2020-01-29 08:34

I know it is an old post. But to detect if a value is in a set of values we can manipulate through array indexOf() which searches and detects the present of the value

var myString="this is my large string set";
var myStr=myString.split(' ');
console.log('myStr contains "my" = '+ (myStr.indexOf('my')>=0));
console.log('myStr contains "your" = '+ (myStr.indexOf('your')>=0));

console.log('integer example : [1, 2, 5, 3] contains 5 = '+ ([1, 2, 5, 3].indexOf(5)>=0));

查看更多
登录 后发表回答