-2

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;
         count++;
    }
 }

 //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?

Zulu
  • 81
  • 3
  • 10
  • 3
    look for array#includes or array#indexOf or array#find ... and many other methods – Jaromanda X Aug 27 '17 at 23:16
  • Possible duplicate of https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript?rq=1 – Zachary Espiritu Aug 27 '17 at 23:17
  • You can `break` from your loop just like `||` shortcuts when it found something, so that it won't take a while. – Bergi Aug 27 '17 at 23:30
  • I don't want to break though, I want to find all possible values by using the | | operator and return the ones that have been found – Zulu Aug 27 '17 at 23:47

2 Answers2

2
if (str.indexOf(stringData) > -1) {
    //found
}

Array.prototype.indexOf() (MDN)

trashr0x
  • 6,457
  • 2
  • 29
  • 39
  • For some reason, I even tried this in console in Chrome but it's only returning the actual index found of the array instead of returning either 0 or -1 when found – Zulu Aug 27 '17 at 23:43
  • 1
    `str.indexOf("c")` will return `2` because `"c"` is the third element in the array (zero-based so the third item is located at index `2`), whereas `str.indexOf("c") > -1` will return `true` because we're asking "does `"c"` exist in `str`?" – trashr0x Aug 27 '17 at 23:53
  • Glad I could help. – trashr0x Aug 27 '17 at 23:57
0

If str is an array, can you do this?

var dataFound = [];
var count = 0;
for(var stringData in someDatabase){
 for (i++; i < str.length; i++) {
  if(stringData == str[i]){
     dataFound[count] = stringData;
     count++;
  }
 }

}

  • I can do that but that's going to take (n)th time to search for where as I can use or operator **||** for each str value to be found in the database so it will only iterate once since we're looking for several values at once for each array in someDatabase – Zulu Aug 27 '17 at 23:42