Flex : How to remove Duplicates from an Array

On January 7, 2008, in Flex, by Anuj Gakhar

If you have an Array and you want to get rid of duplicates from the array, here is a little function you can use to achieve the same.

private function removeDuplicates(arr:Array):Array
var currentValue:String = "";
var tempArray:Array = new Array();
function(item:*, index:uint, array:Array):void {
if (currentValue != item) {
currentValue= item;
return tempArray.sort(Array.CASEINSENSITIVE);

Basically, all its doing is making use of the forEach function built in Flex that runs a custom function for every item in the Array. This function then sorts the data alphabetically, checks each value with the previous value and if they are not same, adds the unique element to the new tempArray and thats what gets returned.

Might be useful for some I guess!

Tagged with:  

6 Responses to Flex : How to remove Duplicates from an Array

  1. Mur4k says:

    var arr:Array = [1,3,2,22,1,4,5,6,4,3,5,6,2,3,4,1,4,6,4,10,3,10,”a”,”a”];
    trace( arr.filter(function(e:*, i:int, a:Array):Boolean {return a.indexOf(e) == i;}) );

  2. Deepak says:

    Its exactly what i m googling for.
    Thanks a lot

  3. I’ve just trashed my filter class after seen your function… simple and effective!

    Thanks for sharing!

  4. Alexandre says:

    Excelent. Thank’s

  5. jm says:

    Anuj, this seems like it could work, but did not happen to work for me. Is there a way to specify which data element in the array to sort on, for instance, an ID?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 445 other subscribers

© 2011 Anuj Gakhar
%d bloggers like this: