jQuery 比较jquery中的两个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17856846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:05:40  来源:igfitidea点击:

Comparing two arrays in jquery

javascriptjquery

提问by user2137186

Using this code...

使用此代码...

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

...I am able to find which element of Array "a" is not in Array "b".

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

Now I need to find:

现在我需要找到:

  • if an element of Array "a" is in Array "b"
  • what is its index in Array "b"
  • 如果数组“a”的元素在数组“b”中
  • 它在数组“b”中的索引是什么

For example "Random data" is in both arrays, so I need to return its position in Array b which is zero index.

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

回答by Matthias Holdorf

Regarding your comment, here is a solution:

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

withjQuery:

使用jQuery:

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

withoutjQuery:

没有jQuery:

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

回答by user1983983

You could just iterate over a and use Array.prototype.indexOfto get the index of the element in b, if indexOfreturns -1b does not contain the element of a.

Array.prototype.indexOf如果indexOf返回-1b 不包含 a的元素,则可以迭代 a 并使用它来获取 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);
});

回答by Vivek Pradhan

This should probably work:

这应该可以工作:

  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 */ 
 }

So your final array would be something like:

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

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

Hope it helps

希望能帮助到你

回答by L10

You can try this:

你可以试试这个:

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

回答by Prince Prasad

Convert both array to string and compare

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

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