Last active
December 17, 2015 15:09
-
-
Save zdfs/5629935 to your computer and use it in GitHub Desktop.
Get unique values of an 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
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