Saturday, November 12, 2011

My Favorite Javascript Method for Removing Array Duplicates


var dedup = function(a)
  {
    var b = [], //create a replacement array
        i=a.sort().length; //get the dups together
    while(i--) //loop down the original array
      {
        // they are bunched, so copy only non matches
        if(a[i]!==a[i-1])
          {
            b[b.length] = a[i];
          }
      }
    return b; // return the replacement array
  }
// test it
console.log('Original Array: bob,sally,9,sally,george,george,andrew,23,230,\'23\'\n' + 'Deduped Array:'+ dedup(['bob','sally',9,'sally','george','george','andrew',23,230,'23']));

No comments:

Post a Comment