如何在2个数组中找到相似性

时间:2014-09-03 08:17:12

标签: jquery arrays compare

我有2个阵列:

var arr1 = ['2','3','4'];
var arr2 = ['2'] or ['2', '3'] or ['2','3','4'] or ['3', '4', '5'] or ['5','6'];

如果arr2与arr1的相似性返回true,如果不相似,如['5','6']则返回false,当arr2为['3','4','5']时,返回false。 / p>

3 个答案:

答案 0 :(得分:0)

只需使用JSON.stringify(arr)

var arr1 = ['2','3','4'];
var arr2 = ['2','3','4'] ;
var i= JSON.stringify(arr1) === JSON.stringify(arr2);
alert(i);

答案 1 :(得分:0)

你也可以这样做

var array1 = ['2', '3', '5', '7'];
var array2 = ['3','9', '8'];
var diff = []; 
$.grep(array2, function( value, key ) {
   if($.inArray(value, array1) === -1){
    diff.push(value);
  }
});
if(diff.length > 0){
   console.log('diff Array is');
   console.log(diff); 
   console.log('Array2 is not a subset of Array1');
}else{
   console.log('Array2 is a subset of Array1'); 
}

JSFIDDLE

答案 2 :(得分:-1)

var arr1 = ['2', '3', '5', '7'];
var arr2 = ['3', '4', '8'];

for(i=0; i<arr2.length; i++){

    if(jQuery.inArray(arr2[i], arr1)== -1){
        console.log(arr2[i] + ' Is not in Arr1');
    }

}

4不在Arr1中 8不在Arr1