Fast Algorithm To Find Unique Items in JavaScript Array

Fast Algorithm To Find Unique Items in JavaScript Array.

 O(2n)

Array.prototype.unique = function() {    var o = {}, i, l = this.length, r = [];    for(i=0; i<l;i+=1) o[this[i]] = this[i];    for(i in o) r.push(o[i]);    return r;};

classic method O(n²)

Array.prototype.unique = function() {    var a = [], l = this.length;    for(var i=0; i<l; i++) {        for(var j=i+1; j<l; j++)            if (this[i] === this[j]) j = ++i;        a.push(this[i]);    }    return a;};
Array.prototype.unique = function(){
return this.filter(function(s, i, a){ return i == a.lastIndexOf(s); });
}
Array.prototype.unique = function(){
return Object.keys(this.reduce(function(r,v){ return r[v]=1,r; },{}));
}
Array.prototype.unique = function(){var len = this.length,a = [],item,i=0;
for(;i</len;)
Array.prototype.unique = function(){
  var len = this.length,
      elems = [],
      elemsLen = 0,
      table ={},
      i;
  for(i=0;i<len;i++){ if(!table[this[i]]){="" pre="" return="" table[this[i]]="1;" this.length="elemsLen;" this;="" this[elemslen++]="this[i];" }="" }</len;i++){
object:Array.prototype.unique = function(){
  var len = this.length,
         elems = [],
         elemsLen = 0, 
       table ={},
         i;  for(i=0;i<len;i++){ code="" if(!table[this[i]]){="" return="" table[this[i]]="1;" this.length="elemsLen;" this;="" this[elemslen++]="this[i];" }="" }</len;i++)
Array.prototype.markDuplicates = function() {
var o = {}, i, l = this.length, r = [];
for(i=0; i= 0) {
o[this[i]] += 1;
r.push(this[i] + ' ' + o[this[i]]);
}
else {
o[this[i]] = 0;
r.push(this[i]);
}
}
return r;
};
// Usage would look like
var myArr = ['Kevin', 'Kevin', 'Shamasis', 'Kevin'],
newArr = myArr.markDuplicates();
Array.prototype.strUnique = function() {
var o = {}, i, l = this.length, r = [];
for(i=0; i<l;i++) o[this[i]] = null;
for(i in o) r.push(i);
return r;
};
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s