spudly.shuoink.com

the best way to predict the future is to implement it

Entries Comments


Array.unique();

31 May, 2008 (09:07) | JavaScript

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

 Array.grep »

Comments

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.

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!

Write a comment