Zulu Zulu - 1 year ago 57
Javascript Question

Creating an if-statement without hard-coding

I have an array that I want to check, for example:

var str = ["a","b","c","d","e","f"];

but I want check if this array's string values are in a database or of some sort. I want to find out which one matches and store the found matches inside an array.

var dataFound = [];
var count = 0;
for(var stringData in someDatabase){
if(stringData == str[0] || stringData == str[1] ...etc){
dataFound[count] = stringData;

//someDatabase will consist of strings like random alphabets
from a-z

I don't want to hardcode the if-statement because a query array can be anywhere from a, b, c .. (n) as n can represent any amount of strings. I tried to use a for-loop from 0 to str.length but that can take quite a while when I can use or operator to search in one go with all the string values, is there a way around this?

Answer Source
if (str.indexOf(stringData) > -1) {

Array.prototype.indexOf() (MDN)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download