Archive for June 7, 2009

Flex Removing Duplicates from an ArrayCollection [Filter function]

I needed a Filter function to remove duplicate items from an Array Collection so I thought Iā€™d do a quick post to share the code.

< ![CDATA[
import mx.collections.ArrayCollection;

private var tempObj:Object = {};

private var filterBtnCol:ArrayCollection = new ArrayCollection(
[{label:”Frank Black”}, {label:”NOFX”}
, {label:”Jawbreaker”}, {label:”Frank Black”}, {label:”NOFX”}, {label:”Jawbreaker”}
, {label:”Frank Black”}, {label:”NOFX”}, {label:”Jawbreaker”}]

private function filterCollection():void {
// assign the filter function
filterBtnCol.filterFunction = deDupe;
//refresh the collection

private function deDupe(item:Object):Boolean {
// the return value
var retVal:Boolean = false;
// check the items in the itemObj Ojbect to see if it contains the value being tested
if (!tempObj.hasOwnProperty(item.label)) {
// if not found add the item to the object
tempObj[item.label] = item;
retVal = true;

return retVal;
// or if you want to feel like a total bad ass and use only one line of code, use a tertiary statement šŸ˜‰
// return (tempObj.hasOwnProperty(item.label) ? false : tempObj[item.label] = item && true);