Skip to content

Instantly share code, notes, and snippets.

@Mottie
Created July 2, 2010 15:30
Show Gist options
  • Save Mottie/461516 to your computer and use it in GitHub Desktop.
Save Mottie/461516 to your computer and use it in GitHub Desktop.
Return Unique Array
/* 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