0

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?

1

3 Answers 3

2

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');
     }
}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, this is really helpful! getting this to a more abstract level - do you also have a solution for this when myAnimal is an array with regular expressions instead of the above mentioned strings?
1

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);

3 Comments

Upvoted your answer since it's also a working approach. It just takes a little less time then the loop approach above.
It's actually O(n), and much faster than having a loop inside a loop O(n^2)
I meant the other way around, my bad. Edited comment.
0
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>");
        }
    }
}

1 Comment

While code alone may answer the question, it is always best to provide an explanation and any relevant resources as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.