Comparing two arrays in jquery

前端 未结 5 2158
臣服心动
臣服心动 2020-12-20 02:46

Using this code...

var a = [\'volvo\',\'random data\'];
var b = [\'random data\'];
var unique = $.grep(a, function(element) {
    return $.inArray(element, b         


        
相关标签:
5条回答
  • 2020-12-20 03:26

    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);
    });
    
    0 讨论(0)
  • 2020-12-20 03:27

    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); 
    })
    
    0 讨论(0)
  • 2020-12-20 03:40

    Convert both array to string and compare

    if (JSON.stringify(a) == JSON.stringify(b))
    {
        // your code here
    }
    
    0 讨论(0)
  • 2020-12-20 03:50

    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

    0 讨论(0)
  • 2020-12-20 03:51

    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 ) );
        }
    });
    
    0 讨论(0)
提交回复
热议问题