Removing Duplicates from Arrays in AS3
Tue Apr 20 06:09:33 2010
Of late, I haven't been posting much on here because I am a little bogged down with work right now. I'm working on a few projects at the same time which is really taking up all of my time. One such project, however, gave me an interesting problem whereby I needed to remove duplicates from an array that was being looped, and on each loop items in the array were removed from the flash display list. Thus, if the same item was found again in the array during another loop and didn't exist anymore in the display list, it caused an error. Here's how I got around it.
package{ import flash.display.*; public class Main extends MovieClip{ public function Main(){ var array:Array = ["1973", "1963", "1999", "1879", "1879", "1963", "1999", "1973"]; trace(array); //traces the original array in which each item occurs twice; var newArray:Array = removeDuplicates(array); trace(newArray);//traces 1973,1963,1999,1879 } private function removeDuplicates(array:Array):Array{ for (var i:uint = array.length; i > 0; i--){ if (array.indexOf(array[i-1]) != i-1){ array.splice(i-1,1); } } return array; } } }
Pretty simple really. All that's happening is that we loop backwards through the array we pass into the removeDuplicates function. While we move backwards through the array, we use indexOf
to find the chronological value at i, and thus if any values found at the end of the array match elsewhere in the array but the indexes don't, the one at the end of the array gets pulled or "spliced" from the array. If you think about it, it makes sense.
I'm pretty sure someone will find a need for this. Hope it helps.
Tweet← back