在jquery中比较两个数组

时间:2013-07-25 11:33:54

标签: javascript jquery

使用此代码......

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”
  • Array“b”
  • 中的索引是什么

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

5 个答案:

答案 0 :(得分:4)

关于你的评论,这是一个解决方案:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

这应该可行:

  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.

希望有所帮助

答案 3 :(得分:1)

你可以试试这个:

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

答案 4 :(得分:0)

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

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