Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

Most efficient JavaScript way to verify if variable matches any value in the list?

I need to test if a variable is any one of the following:

botwsitecoredevcms
botw-web
accountopening
wuatlive
wuat2live
wuat3live
testlive1
testlive2
testlive3
testhoplive1
testhoplive2
testhoplive3
wwwstage
www
blog
mobile

What is the most efficient way to do this? Regex? If so what would the regex be?

Thanks!
ASKER CERTIFIED SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The "contains" function I've used above is as suggested in a comment here: https://css-tricks.com/snippets/javascript/javascript-array-contains/

The code is tested and working (you can see the output in your browser console).
Avatar of MJ

ASKER

Hi Terry,
I'm looking for optimal performance. Would this approach be the optimal way?

Thanks!
It's probably very close to optimal for a list of the given length, and should be extremely fast. It's an order-n-squared algorithm though, so a very long list will start to cause poor performance.
Avatar of MJ

ASKER

The list will get a lot longer than I posted here. Maybe 2-3 times as long?
That should be fine then.