Created
January 11, 2013 15:51
-
-
Save geraintluff/4511695 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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