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\",\
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]
Here's an alternative using underscore.js:
function inAButNotInB(A, B) {
return _.filter(A, function (a) {
return !_.contains(B, a);
});
}