/ Published in: JavaScript
URL: http://jsfiddle.net/ARnL3/
Simple function that filters out any duplicate items in an array.
Expand |
Embed | Plain Text
var unique = function(origArr) { var newArr = [], origLen = origArr.length, found, x, y; for ( x = 0; x < origLen; x++ ) { found = undefined; for ( y = 0; y < newArr.length; y++ ) { if ( origArr[x] === newArr[y] ) { found = true; break; } } if ( !found) newArr.push( origArr[x] ); } return newArr; } var myarray = ['jeffrey', 'allie', 'patty', 'damon', 'zach', 'jeffrey', 'allie', 'patty', 'damon', 'zach', 'joe']; myarray = unique(myarray); alert(myarray.join(', '));
Comments
Subscribe to comments
You need to login to post a comment.

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.
Oops, scratch that. I read the code wrong. Sorry, !found definitely makes more sense because you are trying to avoid duplicates.
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(', '));
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; }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 =undefinedy = 0 while y < newArr.length found = true if origArr[x] is newArr[y] y++ newArr.push origArr[x] unless found x++ newArr