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