Created
May 22, 2013 18:55
-
-
Save zdfs/5629982 to your computer and use it in GitHub Desktop.
Get duplicate values of an Array
This file contains hidden or 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
// Most of this code is from an answer to a question in | |
// Rebecca Murphey's JS Assessment project | |
// https://github.com/rmurphey/js-assessment (thanks, Rebecca!) | |
Array.prototype.duplicate = function() { | |
var seen = {}, // Object to keep track of duplicate occurrences | |
ret = [], // Our return array, with the duplicated values | |
i, l; // iterator vars | |
for (i = 0, l = this.length; i < l; i+=1) { | |
// for each value, we create a has that gets incremented | |
// if the value is duplicated. | |
seen[this[i]] = seen[this[i]] ? seen[this[i]] + 1 : 1; | |
} | |
for (item in seen) { | |
// Iterating over the properties of the seen object, | |
// let's check if the the property is a member of the object | |
// and if the associated value is greater than one (a duplicate) | |
if (seen.hasOwnProperty(item) && seen[item] > 1) { | |
// I like to convert numbers back to actual numbers | |
// otherwise, the duplicate array will return numbers cast as strings | |
item = parseFloat(item) ? parseFloat(item, 10) : item; | |
// if it is, push it to our return array | |
ret.push(item); | |
} | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment