So I came across a situation where I had a whole bunch of items in a collection, and I needed to know how many of each kind there were. In other words, I needed to know the number of each unique element in an IList, Array, ArrayCollection, or what-have-you. I looked for some help online, and fiddled around and got it working. Then a few weeks later I had to do the same thing, and darn near forgot how I did this. Here is the trick – SORT!
Sort the items in the array (alphabetically, numerically, chronologically, etc…) so that unique items are grouped together. Then simply loop over the collection counting identical items, and when a new item occurs, make a note of how many you have of the first item, and start counting again. Below is a quick example. Click “Generate” to create a list of 50 items, where each item is going to be a fish, cat, dog or pony. Then click “Count” to count the number of each one. Also notice how the original list is now sorted so all the ‘dogs’ and ‘cats’ are together.
Sorry, either Adobe flash is not installed or you do not have it enabledHere’s the meat of the code:
//Sort Newlist Alphabetically
newList.sort();
/* Create an object to keep track of each unique item in the array. For example
* { Name: 'cat'
* Value: 7 }
*/
var countObject:;
//Create a var to store the previously examined item in the list.
var previousItem:;
//Loop over all the items in the newArray
for each ( var currentItem: in newList )
{
//If the current item in the list is different from the previous item, then create a new countObject and start counting the new item.
if (previousItem == null || currentItem != previousItem)
{
//Create a new object
countObject = new ();
//Set the name to the current item in the loop
countObject.name = currentItem;
//Count this item
countObject.value = 1;
//Put the object in the sorted list so we can see it later
sortedList.push(countObject);
//Done. Set the current item to the previous item.
previousItem = currentItem;
}
else //Otherwise, we haven't switched to a new item yet, so keep counting the current item.
{
/* Find the last countObject in the sortedList, then add 1 to the value of that object.
* For example, if we have looped over 3 cat items in a row, and the current item is also cat, then:
* { Name: cat, Value: 3 + 1 }
*/
sortedList[sortedList.length - 1].value += 1;
}
}
and Full Source for the above example.