Skip to content

Instantly share code, notes, and snippets.

@jimfleming
Created November 10, 2010 16:19
Show Gist options
  • Save jimfleming/671061 to your computer and use it in GitHub Desktop.
Save jimfleming/671061 to your computer and use it in GitHub Desktop.
Some useful array extensions (dependent on javascript 1.6)
Array.prototype.intersect = function(b) {
return this.filter(function(n) {
return (b.indexOf(n) != -1);
});
}
Array.prototype.diff = function(a) {
return this.filter(function(n) {
return !(a.indexOf(n) > -1);
});
}
Array.prototype.unique = function() {
var a = this.concat();
for (var i = 0; i < a.length; i++)
for (var j = i + 1; j < a.length; j++)
if (a[i] === a[j])
a.splice(j, 1);
return a;
}
Array.prototype.union = function(b) {
return this.concat(b).unique()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment