-6

Hi I have written below code

function unique(th){
   var obj = {};
   for(var i = 0, n = th.length; i < n ; i++){
       obj[th[i]] = th[i];
   }    
   obj.length = n ;
   return Array.prototype.slice.call(obj);
}

But, this is giving me unwanted output. Please help me to correct this. here is the fiddle.

Exception
  • 8,111
  • 22
  • 85
  • 136

2 Answers2

1

I don't know what was your logic so I build a slightly different and working function, trying to make it as clear as possible :

function unique(th){
   var yetseen = {};
   var newarray = [];
   for(var i = 0, n = th.length;  i < n ; i++){
       var val = th[i];
       if (!yetseen[val]) {
           yetseen[val] = true;
           newarray.push(val);
       }
   }    
   return newarray;
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

Use Underscore.js

It's a library with a host of functions for manipulating arrays.

_.uniq

_.uniq(array, [isSorted], [iterator]) Alias: unique Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.

Example

alert(_.uniq([2,2,1,4,5,6,2,9,1,1,6,3,2,1,9,6,4], false)​);​ //yields 2,1,4,5,6,9,3

Brandon Boone
  • 16,281
  • 4
  • 73
  • 100