OT: Remove duplicate values in an array, AS3

Completely off-topic, but I thought I’d post this up in case anyone searching has the same problem as me. I was trying to work out how to take an array, and remove duplicate (triplicate, etc, etc) entries.

Searched google for ages and could only find solutions which would remove only one ‘instance’ of a multiple entry and not the third, fourth, fifth etc, or only remove multiples of the same value if they were next to each other, or sort the array alphabetically and then test the value at index -1, which doesn’t really work either. Plus they were all loops within loops which always messes with my karma.

Anyway – I finally fixed it myself using the nice shiny new array.some() method in Actionscript 3.  Actually I suppose this also loops within a loop – but at least you don’t have to see it! Here’s the code:

//——————————————————————–

var originalArray:Array = new Array(“yellow”, “red”, “blue”, “red”, “yellow”, “green”, “yellow”, “purple”, “ginger”, “red”, “blue”);
var dedupedArray:Array = new Array();

function ArrayTest() {
for each (var colour:String in originalArray){
var tempValue:String = colour;
if(dedupedArray.some(hasDupes)==false){
dedupedArray.push(tempValue);
}
}
function hasDupes(element:String, index:int, array:Array):Boolean {
return (element == tempValue);
}

trace(“dedupedArray: “+dedupedArray);

}
ArrayTest();

//——————————————————————————

Dan will be proud of me!

6 Responses to “OT: Remove duplicate values in an array, AS3”

  1. Ron Says:

    THANKS YOU SOO MUCH!!!!
    I don’t 100% understand this but it works, ill have to study it a bit more, again thanks so much i did a bit of googling to find you!

  2. puelogames Says:

    works perfect!!!

  3. Jacob Says:

    I can’t believe you figured that out!
    Nice job man. I didn’t think anyone could do it!

  4. as-flash Says:

    May be below code would be more simple and clear:

    var originalArray:Array = new Array(“yellow”, “red”, “blue”, “red”, “yellow”, “green”, “yellow”, “purple”, “ginger”, “red”, “blue”);

    var dedupedArray:Array = new Array();

    function ArrayTest()
    {
    for each (var colour:String in originalArray)
    {
    if (dedupedArray.indexOf(colour)===-1)
    {
    dedupedArray.push(colour);
    }
    }
    trace(“dedupedArray: “+dedupedArray);
    }

    ArrayTest();

  5. Neil Says:

    Haven’t tested it, but I’m sure you’re right – thanks!

    Neil

  6. as-flash Says:

    Thank you too for example of using array.some() ;)

Leave a Reply