Skip to content

Instantly share code, notes, and snippets.

@geraintluff
Created January 11, 2013 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geraintluff/4511695 to your computer and use it in GitHub Desktop.
Save geraintluff/4511695 to your computer and use it in GitHub Desktop.
Array.prototype.unique = function () {
// make sure we have a unique string that is not a defined key in any object
var uniqueString = "" + Math.random();
for (var i = 0; i < this.length; i++) {
if (typeof this[i] == "object" && this[i][uniqueString] != undefined) {
uniqueString = "" + Math.random();
i = -1;
continue;
}
}
var result = [];
var accountedFor = {};
for (var i = 0; i < this.length; i++) {
var item = this[i];
if (typeof item == "object") {
if (!item[uniqueString]) {
result.push(item);
item[uniqueString] = true;
}
} else {
var key = (typeof item) + item;
if (!accountedFor[key]) {
result.push(item);
accountedFor[key] = true;
}
}
}
// Now remove the unique string from any objects we stuck it into
for (var i = 0; i < this.length; i++) {
var item = this[i];
if (typeof item == "object") {
delete item[uniqueString];
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment