AS3: Removing duplicates from an array
Just for shiggles (yes, I said it.), removing duplicate items from an array in one line of ActionScript 3:
var arr:Array = ["a","b","b","c","b","d","c"];
var z:Array = arr.filter(function (a:*,b:int,c:Array):Boolean { return ((z ? z : z = new Array()).indexOf(a) >= 0 ? false : (z.push(a) >= 0)); }, this);
trace(z);


October 22nd, 2008 at 11:33 pm
Thanks for the script!
I've been trying all sorts of things to cut out duplicates, but I'm not a programmer so it's been taking me forever!
Simon.
December 4th, 2008 at 5:06 am
well, it's hell of a long line of code.
December 15th, 2008 at 2:56 pm
what about
var a:Array = ["1", "1", "3", "3"];
trace(a.filter(function(e, i, a) {
return a.indexOf(e) == i;
}, this));
?
December 19th, 2008 at 11:30 pm
Wow, that is inline to the extreme. Nice work but it doesn't always have to be on one line
(thanks for the function)
February 26th, 2009 at 3:14 pm
Can you explain how it works so us lames can understand whats going on? Thanks =)
March 10th, 2009 at 3:45 pm
yeah, please
i only half understand it
April 16th, 2009 at 6:18 am
It works perfectly! Wish I could understand how it works.
May 22nd, 2009 at 5:08 am
Razorberry's code:
- Adds the first element into the new array
- Any subsequent element gets tested whether it already exists or not. If not, pushes the element into the new array.
On the other hand, saulo's code is much more elegant:
- Each element's index is compared to the index of its first occurrence. If they're different, it means the element is not the first, thus a duplicate.
May 22nd, 2009 at 5:15 am
A note about performance:
saulo's code is about 2% faster then Razorberry's.
Also, if saulo would add variable types, the code would get a 10% performance boost. Like this:
arr.filter(function(e:*, i:int, a:Array):Boolean {return a.indexOf(e) == i;});
May 22nd, 2009 at 8:44 am
Thanks for your findings Aurelain. I originally posted this as an interesting snippet and made no claims for performance. In a real world application, I would definitely recommend using something a little more readable/sensible.