简体   繁体   中英

Comparing two arrays in jquery

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".

Now I need to find:

  • if an element of Array "a" is in Array "b"
  • what is its index in Array "b"

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

Regarding your comment, here is a solution:

with jQuery:

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

without jQuery:

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

You could just iterate over a and use Array.prototype.indexOf to get the index of the element in b, if indexOf returns -1 b does not contain the element of 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);
});

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

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

Convert both array to string and compare

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM