Reputation: 1
I only have a basic understanding of coding and hope for your help. I have this js code giving me a true false log for all sausage dog occurrences in the array:
var myAnimal = "Sausage Dog";
var arrayAnimal =["Sausage Dog", "Tiger", "Sausage Dog", "Crocodile", "Lion"];
for (var i = 0; i < arrayAnimal.length; i++) {
if(myAnimal == arrayAnimal[i]) {
console.log("True");
} else {
console.log("False");
}
}
How would I do the same task if var myAnimal
was an array with multiple strings?
So it would check every animal in myAnimal
against every animal in var arrayAnimal
and return a true/false for all occurrences.
Is there a way of doing that?
Upvotes: 0
Views: 47
Reputation: 1
var myAnimal = ["Sausage Dog", "Tiger", "Sausage", "Crocodile", "Lion"];
var arrayAnimal =["Sausage Dog", "Tiger","Crocodile", "Lion"];
for (var i = 0; i < myAnimal.length; i++) {
for (var j = 0; j < arrayAnimal.length; j++) {
if (myAnimal[i] == arrayAnimal[j]) {
$('#demo').append("True</br>");
}
}
}
Upvotes: 0
Reputation: 191976
Create a dictionary from the myAniml
array using Array#reduce
, and then Array#map
the arrayAnimal
using the dictionary.
var myAnimal = ["Sausage Dog", "Lion"];
var myAnimalDict = myAnimal.reduce(function(dict, str) {
dict[str] = true;
return dict;
}, Object.create(null));
var arrayAnimal =["Sausage Dog", "Tiger", "Sausage Dog", "Crocodile", "Lion"];
var result = arrayAnimal.map(function(str) {
return !!myAnimalDict[str];
});
console.log(result);
Upvotes: 1
Reputation: 3820
Something like this:
Loop the myAnimal
array inside the arrayAnimal
loop - checking them for equality.
var myAnimal = ["Sausage Dog", "Tiger"];
var arrayAnimal = ["Sausage Dog", "Tiger", "Sausage Dog", "Crocodile", "Lion"];
for (var i = 0; i < arrayAnimal.length; i++) {
for (var j = 0; j < myAnimal.length; j++) {
if(arrayAnimal[i] == myAnimal[j]) console.log('match');
}
}
Upvotes: 2