Count the occurrences of an item in a List or Array

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 enabled

Here’s the meat of the code:

sortedList = new ();

//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.

6 Comments

  1.  ( 2013.02.2 19:18 ) : 山不灵在测试时又发现wordpressl过滤embed标签,经过山不灵多方测试,终于搞定,只要增加一下代码: embed’ => array( src’ => array (), type’ => array (), allowscriptaccess’ => array (), afeswlullocreln’ => array (), wmode’ => array (), width’ => array (), height’ => array ()),希望对朋友们有帮助,也给自己作一个记录。

  2. Antoine : J’adore Rachida Dati : ELLE est une GRANDE Dame et la critiquer ne fera évoluer personne… … la louer non plus ! Jesús, l’occasion de dépoussiérer l’adjectif malagauche…

  3. I don’t see how you can deny Fonzworth Bentley here even if you been hating him up to now. He did his thing.“The first Bad Boy that went G.O.O.D., never left the hood, I lift up hoods”G.O.O.D. Music RoseWood too of course, not sure why Bentley wasn’t apart of that

  4. The irrational comment of "the Grem" wholly in conflict with the facts, is an example of what hate and bigotry does to the mental faculties. This phenomenon was at work in the Taoiseach's notorious "speech" attacking the Holy See. By the way, I understand that there is to be a protest against the closure of the embassy outside the Dail at 2 pm on 8 December.

  5. It doesn’t just autopilot, it also judges your life

  6. PragnÄ™, aby p.Agata pofrunęła na Kanary. Kuchnie i tradycje kulinarne pozostaÅ‚ych propozycji sÄ… u nas stosunkowo dobrze znane, a Wysp – nie ! Wiem, że sÅ‚ynÄ…ca z dociekliwoÅ›ci i kobieco-kucharskiej intuicji pani Agata wyrwie z kanaryjskiej kuchni wszystko, co najciekawsze i rzuci nam na stół !!! A wiÄ™c, na Kanary Siostro !Wnet podjemy sobie ostro !

Leave a Reply

Your email address will not be published.

*

© 2017 Eric Terpstra

Theme by Anders NorénUp ↑