<?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 = {};
/**
* 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 {
/* 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;
}
/**
* 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)) {
/* If the keys Object already has this property,
return false and discard this item. */
return false;
} else {
/* Else the keys Object does *NOT* already have
this key, so add this item to the new data
provider. */
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>
Monday, August 6, 2007
Removing duplicate items from an array using the Array.filter() method
source : here
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment