Array.unique();
Here’s a prototype method for the Array object that allows you to get the unique values in an array!
Array.prototype.unique = function() {
var seen = {};
var unique = [];
for ( var i = 0; i < this.length; i++ ) {
if ( !seen[ this[i] ] ) {
unique.push( this[i] );
seen[ this[i] ] = true;
}
}
return unique;
};
var list = [ 1, 1, 1, 2, 2, 3, 4, 4, 5 ]; list = list.unique(); // Now list is [ 1, 2, 3, 4, 5 ]
« Using the XML DOM Without Writing 15,0000 Lines of Code
Comments
Comment from spudly
Time: July 4, 2008, 6:38 am
Mi - Thanks. I try very hard to make my code readable. To know that I succeeded is a great complement!
Comment from Mi
Time: July 4, 2008, 4:08 am
nice, i like the words used on the variables: unique and seen. Added to its readability.