How to check if elements of an array are contained in another JQuery array

0

How can I check if elements of an array are contained in another array?

ex:

array_1 = ['wifi', 'internet'];
array_2 = ['wifi', 'internet', 'telefone', 'email']

How can I tell if array_1 contains array_2 values using JQuery?

    
asked by anonymous 30.05.2018 / 19:22

2 answers

0

How did :

  

1 - I ran one of the vectors with the for tag.

     

2 - Then already with the values, using the javascript includes method I made the condition to test if the values of one vector already existed in the other.

$(document).ready(function() {
   var array_1 = ['wifi', 'internet'];
   var array_2 = ['wifi', 'internet', 'telefone', 'email'];

   for(var i=0; i<array_1.length; i++) {
      var array = array_1[i];
      if(array_2.includes(array)) {
         console.log('"'+array+'"' + " Existem em ambos vetores.");
      }
      else {
         console.log("Não existem elementos iguais!");       
     }
   }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
30.05.2018 / 20:13
1

I understand that you want to check if all items in an array contain in another array.

You can use filter , where the result of the items found will be stored in a new array, so just check if the size of this array is the same as the first array.

function arrayCompare(first, last)
{
    var result = first.filter(function(item){ return last.indexOf(item) > -1});   
    return result.length;  
}    

array_1 = ['wifi', 'internet'];
array_2 = ['wifi', 'internet', 'telefone', 'email']

console.log(arrayCompare(array_1, array_2) === array_1.length);
    
30.05.2018 / 20:37