Skip to content

Instantly share code, notes, and snippets.

@zdfs
Last active December 17, 2015 15:09
Show Gist options
  • Save zdfs/5629935 to your computer and use it in GitHub Desktop.
Save zdfs/5629935 to your computer and use it in GitHub Desktop.
Get unique values of an Array
Array.prototype.unique = function() {
var unique = {}, // Object to keep track of unique occurrences
ret = [], // Our return array, with unique values
i, l; // iterator vars
for (i = 0, l = this.length; i < l; i+=1) {
// if the unique object already has the current array value,
// skip to the next value of the array
if (unique.hasOwnProperty(this[i])) {
continue;
}
// if we make it this far, the value is unique. Push it
// to the return array.
ret.push(this[i]);
// Once we have this value, make sure the unique object
// knows it's already there.
unique[this[i]] = 1;
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment