<?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()" viewSourceURL="srcview/index.html">
<mx:Script>
<![CDATA[
private var keys:Object = {};
/**
* Called by the Application container's creationComplete
* event handler. This method creates a new Array object
* which will be used as a data provider as well as a
* filtered view of that array which does not contain
* duplicated items.
*/
private function init():void {
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"});
var filteredArr:Array = arr.filter(removedDuplicates);
arrColl.source = arr;
dedupedArrColl.source = filteredArr;
}
/**
* This method is used to filter an array so that no
* duplicate items are created. It works by first
* checking to see if a keys object already contains
* a key equal to the current value of the item.data
* value. If the key already exists, the current item
* will not be readded to the data provider. If the key
* does not already exist, add the key to the keys
* object and add this item to the data provider.
*/
private function removedDuplicates(item:Object, idx:uint, arr:Array):Boolean {
if (keys.hasOwnProperty(item.data)) {
return false;
} else {
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>