Skip to content

Instantly share code, notes, and snippets.

@mogsdad
Created January 9, 2014 18:48
Show Gist options
  • Save mogsdad/8339686 to your computer and use it in GitHub Desktop.
Save mogsdad/8339686 to your computer and use it in GitHub Desktop.
Javascript Array extension to find the members of a set (array) that are unique, that is they are not members of other sets. See http://goo.gl/ArHbvb.
/**
* 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment