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

前端 未结 8 1110
情歌与酒
情歌与酒 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 -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]
    

提交回复
热议问题