Created
July 2, 2010 15:30
-
-
Save Mottie/461516 to your computer and use it in GitHub Desktop.
Return Unique Array
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
/* Return a unique array | |
* myArray = ["ccc","aaa","bbb","aaa"]; | |
* x = myArray.getUnique(); // x = ["ccc","aaa","bbb"] | |
* y = myArray.getUnique(true); // y = ["aaa","bbb","ccc"] | |
*/ | |
// Slightly faster version than getUnique2; Modified from | |
// http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/ | |
Array.prototype.getUnique1 = function(s){ | |
var c, a = [], o = {}, i, j = 0, l = this.length; | |
for(i=0; i<l; ++i){ | |
c = this[i]; | |
if (!o[c]) { | |
o[c] = {}; | |
a[j++] = c; | |
} | |
} | |
return (s) ? a.sort() : a; | |
}; | |
// original script | |
Array.prototype.getUnique2 = function(s){ | |
var u = {}, a = [], i, l = this.length; | |
for(i = 0; i < l; ++i){ | |
if(this[i] in u) { continue; } | |
a.push(this[i]); | |
u[this[i]] = 1; | |
} | |
return (s) ? a.sort() : a; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment