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!
January 16th, 2009 at 00:45
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!
February 16th, 2009 at 13:27
works perfect!!!
September 18th, 2009 at 18:07
I can’t believe you figured that out!
Nice job man. I didn’t think anyone could do it!
October 21st, 2009 at 09:18
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();
October 21st, 2009 at 09:46
Haven’t tested it, but I’m sure you’re right – thanks!
Neil
October 21st, 2009 at 09:51
Thank you too for example of using array.some()