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

前端 未结 8 1033
情歌与酒
情歌与酒 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 07:09

    This is a late answer, but it uses no libraries so some may find it helpful.

    /**
     * Returns a non-destructive Array of elements that are not found in
     * any of the parameter arrays.
     *
     * @param {...Array} var_args   Arrays to compare.
     */
    Array.prototype.uniqueFrom = function() {
      if (!arguments.length)
        return [];
      var a1 = this.slice(0); // Start with a copy
    
      for (var n=0; n < arguments.length; n++) {
        var a2 = arguments[n];
        if (!(a2 instanceof Array))
          throw new TypeError( 'argument ['+n+'] must be Array' );
    
        for(var i=0; i<a2.length; i++) {
          var index = a1.indexOf(a2[i]);
          if (index > -1) {
            a1.splice(index, 1);
          } 
        }
      }
      return a1;
    }
    

    Example:

    var sheetUsers = ['joe@example.com','fred@example.com','sam@example.com'];
    var siteViewers = ['joe@example.com','fred@example.com','lucy@example.com'];
    var viewersToAdd = sheetUsers.uniqueFrom(siteViewers);  // [sam@example.com]
    var viewersToRemove = siteViewers.uniqueFrom(sheetUsers);  // [lucy@example.com]
    
    0 讨论(0)
  • 2020-11-27 07:13

    Here's an alternative using underscore.js:

    function inAButNotInB(A, B) {
      return _.filter(A, function (a) {
        return !_.contains(B, a);
      });
    }
    
    0 讨论(0)
提交回复
热议问题