Joe's Blog

line

A blog by Joe Billman about programming, and other stuff

line

Remove Duplicates from an Array AS3

Posted on: October 28th, 2011 by Joe

line 2 Comments

I recently needed function that would remove duplicate values from an array. After looking around online and modifying what I found to fit my needs I came up with the following:

var arr:Array = ["a", "b", "c", "a", "d", "a", "a"];

removeDuplicates(arr);

trace(arr);

function removeDuplicates(target:Array):void
{
	for(var i:uint=target.length; i>0; i--)
	{
		if(target.indexOf(target[i-1]) != i-1)
		{
			target.splice(i-1, 1);
		}
	}
}

If you are searching for a way to do this, I hope this helps!

2 Responses

  1. How would you like this simpler version?

    var uniqArray:Array = arr.filter(function(item:String, index:int, array:Array):Boolean {
    return array.indexOf(item) == index;
    });

    That is for array of strings, can use item:* for arbitrary data.

  2. Joe says:

    Thanks Gene, that is a great way of doing it!

Leave a Reply


Warning: Use of undefined constant Y - assumed 'Y' (this will throw an Error in a future version of PHP) in /homepages/16/d145171736/htdocs/php/footer.php on line 1