比较jquery中的两个数组

Comparing two arrays in jquery

本文关键字:两个 数组 jquery 比较      更新时间:2023-09-26

使用此代码。。。

var a = ['volvo','random data'];
var b = ['random data'];
var unique = $.grep(a, function(element) {
    return $.inArray(element, b) == -1;
});
var result = unique ;
alert(result); 

我能够找到数组"a"的哪个元素不在数组"b"中。

现在我需要找到:

  • 如果数组"a"的元素在数组"b"中
  • 它在数组"b"中的索引是多少

例如,"随机数据"在两个数组中,所以我需要返回它在数组b中的位置,即零索引。

关于您的评论,这里有一个解决方案:

使用jQuery:

$.each( a, function( key, value ) {
    var index = $.inArray( value, b );
    if( index != -1 ) {
        console.log( index );
    }
});

不带jQuery:

a.forEach( function( value ) {
    if( b.indexOf( value ) != -1 ) {
       console.log( b.indexOf( value ) );
    }
});

将两个数组转换为字符串并比较

if (JSON.stringify(a) == JSON.stringify(b))
{
    // your code here
}

如果indexOf返回-1,则可以在a上迭代并使用Array.prototype.indexOf来获取b中元素的索引。b不包含a的元素。

var a = [...], b = [...]
a.forEach(function(el) {
    if(b.indexOf(el) > 0) console.log(b.indexOf(el));
    else console.log("b does not contain " + el);
});

这可能会起作用:

  var positions = [];
  for(var i=0;i<a.length;i++){
  var result = [];
       for(var j=0;j<b.length;j++){
          if(a[i] == b[j])
            result.push(i); 
  /*result array will have all the positions where a[i] is
    found in array b */
       }
  positions.push(result);
 /*For every i I update the required array into the final positions
   as I need this check for every element */ 
 }

所以你的最终数组应该是这样的:

  var positions = [[0,2],[1],[3]...] 
  //implies a[0] == b[0],b[2], a[1] == b[1] and so on.

希望它能帮助

你可以试试这个:

var a = ['volvo','random data'];
var b = ['random data'];
$.each(a,function(i,val){
var result=$.inArray(val,b);
if(result!=-1)
alert(result); 
})