Tag: data filtering

Find all unique values from array or collection

Find all unique values from array or collection

I needed a quick/simple method to iterate through a collection of data and pull out just the unique values.
So if you had a collection that looked like





  
  
  
  
  
  
  
  
 
 

Then you only have 3 unique values (A, B & C).

So I came up with a method that is effectively a single pass through the data.
It uses a dictionary, and the value of the objects inside the AC for the key.

So if you have a dictionary variable dict, then if you have a value of ‘XX’ and you use that as the key (dict[‘XX’] = ‘XX’) then if you have another value of ‘XX’ and assign that to dict[‘XX’] = ‘XX’ then the previous entry gets overwritten giving you a set of unique values.

Its just a case of then getting the value out of the dictionary and back into an AC. (dictionary’s are not Bindable like AC’s)

//takes an AC and the filters out all duplicate entries
public function getUniqueValues (collection : ArrayCollection) : ArrayCollection {
	var length : Number = collection.length;
	var dic : Dictionary = new Dictionary();

	//this should be whatever type of object you have inside your AC
	var value : Object;
	for(var i : Number = 0; i < length; i++){
		value = collection.getItemAt(i);
		dic[value] = value;
	}

	//this bit goes through the dictionary and puts data into a new AC
    var unique : ArrayCollection = new ArrayCollection();
    for(var prop : String in dic){
    	unique.addItem(dic[prop]);
    }
    return unique;
}

[ad name="ad-1"]