ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Adobe Flex | ActionScript | How to Find an Item in ArrayCollection Without getItemIndex()

Updated on October 21, 2011

When you try to find an item in an ArrayCollection by using the getItemIndex() method, you will always get a -1 result using a label or string because this method is referencing a different object in memory than the one referenced by the string value even though they may have the same label. That said, you can search for an item in ArrayCollection without using getItemIndex() method in ActionScript. Below I present such a solution. This article walks you through how to setup your code to search for an item in an ArrayCollection using a selected item (combobox) from another ArrayCollection. In the process I will also populate multiple ArrayCollections using the same flat data source. Finally, I include some filtering methods to filter out duplicate values and also selectively filter an item from a Combobox.

To demonstrate these different techniques, I will use the following flat data (the list isn’t complete and if there are any errors, please forgive my ignorance):

var objCountry:Object = {

[region:'North America', country:'Canada'],
[region:'North America', country:'USA'],
[region:'North America', country:'Mexico'],
[region:'South America', country:'Columbia'],
[region:'South America', country:'Venezuela'],
[region:'South America', country:'Bolivia'],
[region:'South America', country:'Chile'],
[region:'South America', country:'Peru'],
[region:'South America', country:'Argentina'],
[region:'South America', country:'Brazil'],
[region:'South America', country:'Ecuador'],
[region:'South America', country:'Uruguay'],
[region:'Europe', country:'France'],
[region:'Europe', country:'Germany'],
[region:'Europe', country:'Italy'],
[region:'Europe', country:'England'],
[region:'Europe', country:'Ireland'],
[region:'Europe', country:'Iceland'],
[region:'Europe', country:'Scotland'],
[region:'Europe', country:'Netherlands'],
[region:'Europe', country:'Belgium'],
[region:'Europe', country:'Finland'],
[region:'Europe', country:'Greece'],
[region:'Europe', country:'Portugal'],
[region:'Europe', country:'Spain'],
[region:'Europe', country:'Sweden'],
[region:'Europe', country:'Hungary'],
[region:'Europe', country:'Austria'],
[region:'Europe', country:'Switzerland'],
[region:'Europe', country:'Poland'],
[region:'Europe', country:'Slovakia'],
[region:'Europe', country:'Albania'],
[region:'Europe', country:'Georgia'],
[region:'Europe', country:'Lithuania'],
[region:'Middle-East', country:'India'],
[region:'Middle-East', country:'Iraq'],
[region:'Middle-East', country:'Lebanon'],
[region:'Middle-East', country:'Israel'],
[region:'Asia', country:'Japan'],
[region:'Asia', country:'China'],
[region:'Asia', country:'Taiwan'],
[region:'Asia', country:'Philippines'],
[region:'Oceania' country:'Australia'],
[region:'Oceania', country:'New Zealand']

};

[Bindable]
var countryList:Array = new Array(objCountry);

[Bindable]
var countryArr:ArrayCollection = new ArrayCollection();

[Bindable]
var regionArr:ArrayCollection = new ArrayCollection();


//create an empty object for the filter function
[Bindable]
var keys:Object = {};



private function AssignData():void
{
	countryArr.source = countryList;
	regionArr.source = countryList;


	var countryCombo:Combobox = new Combobox();
	countryCombo.dataProvider = countryArr
countryCombo.LabelField = 'country';

var regionCombo:Combobox = new Combobox();
regionCombo.dataProvider = regionArr
regionCombo.LabelField = 'region';

	//filter out the duplicate region values
	regionArr.filterFunction = removedDuplicates;
	regionArr.refresh();
}
First I declare an object objCountry and build an array countryList. I assign the array to two ArrayCollections countryArr and regionArr. I am doing this to demonstrate how to take a value from one ArrayCollection to find an index in another ArrayCollection. Also creating a flat data object and assigning it to an array will allow to reset any of the ArrayCollections using the  ArrayCollection.source property to its original list once I cleared out the filter.


Next assign the ArrayCollections to two comboboxes. I do this inside the AssignData function. This function could be added to the ApplicationComplete  property of the Application root element in your mxml file so to setup your ui elements once the application is loaded. Notice how I assign the same flat data to different ArrayCollections and subsequently to different comboboxes using the labelField property of the combobox. The labelField property tells the compiler which element in the ArrayCollection to display.

If you add this code and run it, you will discover that the regionCombobox will have duplicate values since there are multiple countries in the same region in the flat data.  To remove this duplicates, I add a filter function to the regionArr.

This is fairly straightforward function. The API for filter functions require to use an object as parameter in its method signature. keys is only a temporary place holder for the unique values in the ArrayCollection. If you step through the function, you would see that the compiler steps through the filterFunction method in the ArrayCollection class and when it finds a unique it adds this value to an array using the push method. The hasOwnProperty method of the Object class checks to see if a property is defined. In our case it is used to check of the Object keys already has a specific value. If the value is found, the method returns false and doesn’t add the value to the keys Object otherwise the value is added.

Function to Remove Duplicates

private function removedDuplicates(item:Object):Boolean {

// the return value
var retVal:Boolean = false;
// check the items in the item Ojbect to see if it contains the value being tested
if (!keys.hasOwnProperty(item.region)) {
// if not found add the item to the object
keys[item.region] = item;
retVal = true;
}

return retVal;
            
}

Finding values in an ArrayCollection using a value from another ArrayCollection

To find a value in the ArrayCollection, I am going to use the following SelectRegion method. This method  would work well in a combobox which would be triggered on the change event.

private function SelectRegion(e:Event):void
{
	//Get a reference to the item selected in the combobox
	var oRegion:Object = countryArr.getItemAt(e.currentTarget.selectedIndex);

	//Get the region label value
	var sgStr:String = oRegion.region;
	
	/* The following line, included to demonstrate the problem, would return -1 because oRegion.region is not the same Object as the one in the regionArr even if they have the same label */

	var regionIndex:Number = regionArr.getItemIndex(oRregion.region);

//Instead I will loop through the items in the regionArr collection until the label at index --sr-- matches the label selected in the combobox. After that is is easy to identify the index number and set a second combobox.
			
	for(var sr:int; sr < regionArr.length;sr++)
	{
		var ob:Object= regionArr.getItemAt(sr);
		var temp:String = ob.region.toString();
		
		trace(temp);
		trace(sgStr);
		
		//Find the matching label in the countryArr ArrayCollection
		//Use the label as a reference to get the index in the regionArr
		if(temp == sgStr)
		{
		
			this.cbRegion.selectedIndex = sr;
			return;
		
		}
	}
}
Once the label values match up, which is only two strings, it is only a matter of locating the index number using the looping index. This is it for searching and filtering. If you more information or clarification, leave me a comment and I will respond as soon as possible. If you have any suggesting on improving this tutorial, let me know.

Comments

    0 of 8192 characters used
    Post Comment

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

      Hey Kapil Waghe,

      Thanks for the kind words. I am glad that the tutorial was useful :)

      Kevin

    • profile image

      Kapil Waghe 

      6 years ago

      Hey Man,

      Thanks-a-lot.

      Good job, keep it up . :)

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)