Posted By

Nettuts on 12/06/10


Tagged

javascript array filter duplicates nettuts


Versions (?)

Who likes this?

17 people have marked this snippet as a favorite

ichnoweb
amplitude
antti
samkamerer
alyssonweb
spaceploitator
petemcbride
IvanKD
antonioreyna
qubestream
guo3823538
leobetosouza
k3vk4
Sonique
ringo380
stimps0n
adambundy


Remove Duplicate Values from Array


 / Published in: JavaScript
 

URL: http://jsfiddle.net/ARnL3/

Simple function that filters out any duplicate items in an array.

  1. var unique = function(origArr) {
  2. var newArr = [],
  3. origLen = origArr.length,
  4. found,
  5. x, y;
  6.  
  7. for ( x = 0; x < origLen; x++ ) {
  8. found = undefined;
  9. for ( y = 0; y < newArr.length; y++ ) {
  10. if ( origArr[x] === newArr[y] ) {
  11. found = true;
  12. break;
  13. }
  14. }
  15. if ( !found) newArr.push( origArr[x] );
  16. }
  17. return newArr;
  18. }
  19.  
  20. var myarray = ['jeffrey', 'allie', 'patty', 'damon', 'zach', 'jeffrey', 'allie', 'patty', 'damon', 'zach', 'joe'];
  21. myarray = unique(myarray);
  22. alert(myarray.join(', '));

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: AlexWolfe on December 7, 2010

Would it be nice to set found = false; That way you could say if(found) newArr.push instead of if(!found). Both work, just seems like it would be more elegant.

Also, I'm not a big fan of setting vars to undefined. If you set a variable to undefined because if you don't even declare a var its returns undefined.

Posted By: AlexWolfe on December 7, 2010

Oops, scratch that. I read the code wrong. Sorry, !found definitely makes more sense because you are trying to avoid duplicates.

Posted By: ronydee on December 12, 2010

this function extends the Array object and cleans the duplicates from the input Array instead of creating a new one:

Array.prototype.unique = function unique() { var i = 0; while (i < this.length) { var current = this[i]; for (k = this.length; k > i; k--) { if (this[k] === current) { this.splice(k,1); } } i++; } return this; }

var myarray = ['jeffrey', 'allie', 'patty', 'damon', 'zach', 'jeffrey', 'allie', 'patty', 'damon', 'zach', 'joe']; alert(myarray.unique().join(', '));

Posted By: dvdrtrgn on December 14, 2010

Let's golf:

function unique(arr,dup) { dup = dup ? arr.concat() : arr; for (var i=0; i < dup.length; i++) if (dup.indexOf(dup[i]) < i) dup.splice(i--); return dup; }

Posted By: malachaifrazier on November 9, 2012

Well done! I just implemented this in Coffeescript: $ -> unique = (origArr) -> newArr = [] origLen = origArr.length found = undefined x = 0 y = 0 x = 0 while x < origLen found = undefined y = 0 while y < newArr.length found = true if origArr[x] is newArr[y] y++ newArr.push origArr[x] unless found x++ newArr

You need to login to post a comment.