Remove Duplicates from an Array & display in List


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical" verticalAlign="middle" backgroundColor="white" creationComplete="init()">
    <mx:Script>
        <![CDATA[
            private var keys:Object = {};
            private function init():void {
                /* Create a dummy data source with some semi-random data. */
                var arr:Array = [];
                arr.push({data:1, label:"one"});
                arr.push({data:1, label:"one"});
                arr.push({data:1, label:"one"});
                arr.push({data:1, label:"one"});
                arr.push({data:2, label:"two"});
                arr.push({data:2, label:"two"});
                arr.push({data:2, label:"two"});
                arr.push({data:1, label:"one"});
                arr.push({data:3, label:"three"});
                arr.push({data:3, label:"three"});
                /* Filter the original array and call the removeDuplicates() function on each item in the array.*/
                var filteredArr:Array = arr.filter(removedDuplicates);
                arrColl.source = arr;
                dedupedArrColl.source = filteredArr;
            }
            private function removedDuplicates(item:Object, idx:uint, arr:Array):Boolean {
                if (keys.hasOwnProperty(item.data)) {
                    /* If the keys Object already has this property, return false and discard this item. */
                    return false;
                } else {
                 /* Else the keys Object doesN'T already have this key, so add this item 2 the new dataprovider*/
                    keys[item.data] = item;
                    return true;
                }
            }
        ]]>
    </mx:Script>
    <mx:ArrayCollection id="arrColl" />
    <mx:ArrayCollection id="dedupedArrColl" />
    <mx:HBox>
        <mx:VBox>
            <mx:Label text="Original ({arrColl.length} items):" />
            <mx:List dataProvider="{arrColl}" />
        </mx:VBox>
        <mx:VBox>
            <mx:Label text="Filtered ({dedupedArrColl.length} items):" />
            <mx:List dataProvider="{dedupedArrColl}" />
        </mx:VBox>
    </mx:HBox>
</mx:Application>
Advertisements

~ by mjcprasad2000 on January 16, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

 
%d bloggers like this: