Created
October 23, 2010 16:52
-
-
Save Mottie/642431 to your computer and use it in GitHub Desktop.
Return Duplicates from 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
/* 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