AS3: Removing duplicates from an array

Actionscript

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);

This entry was posted on Wednesday, September 3rd, 2008 at 11:22 pm and is filed under Actionscript. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.

11 Responses to “AS3: Removing duplicates from an array”

  1. Simon B Says:

    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.

  2. vitaLee Says:

    well, it's hell of a long line of code.

  3. saulo Says:

    what about
    var a:Array = ["1", "1", "3", "3"];
    trace(a.filter(function(e, i, a) {
    return a.indexOf(e) == i;
    }, this));
    ?

  4. chet Says:

    Wow, that is inline to the extreme. Nice work but it doesn't always have to be on one line :) (thanks for the function)

  5. saicolo Says:

    Can you explain how it works so us lames can understand whats going on? Thanks =)

  6. laku matu Says:

    yeah, please
    i only half understand it

  7. marije Says:

    It works perfectly! Wish I could understand how it works.

  8. Aurelain Says:

    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.

  9. Aurelain Says:

    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;});

  10. Ash Says:

    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.

  11. jaleel Says:

    Pretty good way for filtering. I got how it works :)
    Anybody wants to know how this code works???

Leave a Reply