How to check whether elements of an array are contained in another Jquery array

Asked

Viewed 2,021 times

1

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 know if the values of the array_1 contain in the array_2 using Jquery ?

2 answers

2


As I did:

1 - I traversed one of the vectors with the loop for.

2 - Then already with the values, using the javascript method includes 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>

0

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

You can use the filter, where the result of the found items will be stored in a new array, so just check if the size of this array is equal to 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.