Skip to content

Instantly share code, notes, and snippets.

@zdfs
Created May 22, 2013 18:55
Show Gist options
  • Save zdfs/5629982 to your computer and use it in GitHub Desktop.
Save zdfs/5629982 to your computer and use it in GitHub Desktop.
Get duplicate values of an Array
// 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