Reputation: 11
I am currently trying to program a word game where the player types the words he/she finds into a text box and hits submit. After hitting submit, that word is stored in an array that I can do something with in Javascript, and the textbox is cleared so that they can enter another word. I think I can figure those parts out eventually (I am new to HTML and JavaScript), but I have no idea how to do what I want to do next. I need to check each of the words that the player found against an array of verified words. I have found some codes on here that will search for whether a single word matches any strings an array, but how would I write a code that checks all of the words the player finds against a dictionary/verified array?
Upvotes: 1
Views: 1592
Reputation: 2488
function getIntersect(arr1, arr2) {
var r = [], o = {}, l = arr2.length, i, v;
for (i = 0; i < l; i++) {
o[arr2[i]] = true;
}
l = arr1.length;
for (i = 0; i < l; i++) {
v = arr1[i];
if (v in o) {
r.push(v);
}
}
return r;
}
Upvotes: 0
Reputation: 179
You can iterate over every element in your user array and use IndexOf to see if it exists in your verified array. IndexOf will return -1 if it was not found.
for (var i = 0; i < userArray.length ; i++)
if(verifiedWordArray.indexOf(userArray[i]) == -1)
return false;
return true;
If you have to match specific position, this would do the trick assuming they are both of the same length.
for (var i = 0; i < userArray.length ; i++)
if(userArray[i] != verifiedWordArray[i])
return false;
return true;
Upvotes: 1
Reputation: 11609
If you do it on the client side, you can store your word's dictionary in an array, for instance array= ["one","two", "three","word"]
, and then check if the user's word word
against your dictionary with this array.indexOf('word') > -1
Upvotes: 0
Reputation: 15356
pseudo code:
ans = true // assume the user is right
for (each of the words in user input array){
if(current word is not in the predefined array){ // use .indexOf()
ans = false
break; //stop loop
}
}
Once this loop is done ans
will be true or false according to the user's input.
Upvotes: 0