Advertisement
rg443

javascript array unique

Jan 26th, 2013
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function uniquePrimitives(array){
  2.   var hash = Object.create(null),
  3.       out = [],
  4.       i = array.length;
  5.  
  6.   while (i--) {
  7.     if (!hash[array[i]]) {
  8.       hash[array[i]] = true;
  9.       out.push(array[i]);
  10.     }
  11.   }
  12.  
  13.   return out;
  14. }
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21. var unique = function(){
  22.   var hasOwn = {}.hasOwnProperty,
  23.       uids = {};
  24.  
  25.   function uid(){
  26.     var str = '_' + Math.random().toString(36);
  27.     if (str in uids)
  28.       return uid();
  29.  
  30.     uids[str] = true;
  31.     return str;
  32.   }
  33.  
  34.   function unique(array){
  35.     var strings = {}, numbers = {}, others = {},
  36.         tagged = [], failed = [],
  37.         count = 0, i = array.length,
  38.         item, type;
  39.  
  40.     var id = uid();
  41.  
  42.     while (i--) {
  43.       item = array[i];
  44.       type = typeof item;
  45.       if (item == null || type !== 'object' && type !== 'function') {
  46.         // primitive
  47.         switch (type) {
  48.           case 'string': strings[item] = true; break;
  49.           case 'number':
  50.             if (1 / item === -Infinity)
  51.               // negative zero
  52.               others[item] = item;
  53.             else
  54.               numbers[item] = true;
  55.             break;
  56.           default: others[item] = item; break;
  57.         }
  58.       } else {
  59.         // object
  60.         if (!hasOwn.call(item, id)) {
  61.           try {
  62.             // set key ON each object tagging it as "seen"
  63.             item[id] = true;
  64.             tagged[count++] = item;
  65.           } catch (e){
  66.             if (failed.indexOf(item) === -1)
  67.               failed[failed.length] = item;
  68.           }
  69.         }
  70.       }
  71.     }
  72.  
  73.     // remove the tags
  74.     while (count--)
  75.       delete tagged[count][id];
  76.  
  77.     tagged = tagged.concat(failed);
  78.     count = tagged.length;
  79.  
  80.     // append primitives to results
  81.     for (i in strings)
  82.       if (hasOwn.call(strings, i))
  83.         tagged[count++] = i;
  84.  
  85.     for (i in numbers)
  86.       if (hasOwn.call(numbers, i))
  87.         tagged[count++] = +i;
  88.  
  89.     for (i in others)
  90.       if (hasOwn.call(others, i))
  91.         tagged[count++] = others[i];
  92.  
  93.     return tagged;
  94.   }
  95.  
  96.   return unique;
  97. }();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement