Javascript algorithm to find elements in array that are not in another array

前端 未结 8 1032
情歌与酒
情歌与酒 2020-11-27 06:19

I\'m looking for a good algorithm to get all the elements in one array that are not elements in another array. So given these arrays:

var x = [\"a\",\"b\",\         


        
相关标签:
8条回答
  • 2020-11-27 06:51

    Maybe jLinq can help you?

    It lets you run queries like this against javascript objects.

    For example:

    var users = [ { name: "jacob", age: 25 },  { name: "bob" , age: 30 }]
    var additionalusers = [ { name: "jacob", age: 25 },  { name: "bill" , age: 25 }]
    
    var newusers = jLinq.from(users).except(additionalusers).select();
    
    >>> newusers = [ { name: "bob" , age: 30 } ]
    

    It's a bit overkill for you at the moment, but it's a robust solution that I was glad to learn about.

    It can do intersects, unions, handle boolean logic and all kinds of great linq style goodness.

    0 讨论(0)
  • 2020-11-27 06:52
     findDiff = (A, B) => {
         return  A.filter(function (a) {
              return !B.includes(a);
         });
     }
    
    0 讨论(0)
  • 2020-11-27 06:55
    var z = $.grep(y, function(el){return $.inArray(el, x) == -1}); 
    

    Also, that method name is too short for its own good. I would expect it to mean isElementInArray, not indexOf.

    For a demo with objects, see http://jsfiddle.net/xBDz3/6/

    0 讨论(0)
  • 2020-11-27 06:57

    in ES6 simply

    const x = ["a", "b", "c", "t"];
    const y = ["d", "a", "t", "e", "g"];
    
    console.log( y.filter(e => !x.includes(e)) );

    (another option is y.filter(e => x.indexOf(e)===-1) )

    0 讨论(0)
  • 2020-11-27 06:58

    Make sorted copies of the arrays first. If the top elements are equal, remove them both. Otherwise remove the element that is less and add it to your result array. If one array is empty, then add the rest of the other array to the result and finish. You can iterate through the sorted arrays instead of removing elements.

    // assume x and y are sorted
    xi = 0; yi = 0; xc = x.length; yc = y.length;
    while ( xi < xc && yi < yc ) {
      if ( x[xi] == y[yi] ) {
        xi += 1;
        yi += 1;
      } else if ( x[xi] < y[yi] ) {
        z.push( x[xi] );
        xi += 1;
      } else {
        z.push( y[yi] );
        yi += 1;
      }
    }
    // add remainder of x and y to z.  one or both will be empty.
    
    0 讨论(0)
  • 2020-11-27 07:04

    Late answer with the new ECMA5 javascript:

    var x = ["a","b","c","t"];
    var y = ["d","a","t","e","g"];
    
    myArray = y.filter( function( el ) {
      return x.indexOf( el ) < 0;
    });
    
    0 讨论(0)
提交回复
热议问题