Skip to content

Instantly share code, notes, and snippets.

@Mottie
Created October 23, 2010 16:52
Show Gist options
  • Save Mottie/642431 to your computer and use it in GitHub Desktop.
Save Mottie/642431 to your computer and use it in GitHub Desktop.
Return Duplicates from Array
/* Find & return only duplicates from an Array
* also returned is an object with the # of duplicates found
* myArray = ["ccc", "aaa", "bbb", "aaa", "aaa", "aaa", "aaa", "bbb"];
* x = myArray.getDuplicates();
* // x = [ array of duplicates, associative object with # found]
* // x = [ ['aaa','bbb'] , { 'aaa' : 5, 'bbb' : 2 } ]
* alert(x[0]) // x[0] = ['aaa','bbb'] & alerts aaa,bbb
* alert(x[1]['aaa']) // alerts 5;
*/
Array.prototype.getDuplicates = function(sort) {
var u={},a=[],b={},c,i,l=this.length;
for(i=0;i<l;++i){
c=this[i];
if (c in u) {
if (c in b) { b[c]+=1; } else { a.push(c); b[c]=2; }
}
u[c] = 1;
}
// return array and associative array with # found
return (sort) ? [a.sort(), b] : [a, b];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment