I want to count number of occurances in an array in ActionScript 3.0. Say I have
var item:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];
How can I make it show the number of matching strings? For instance, result: apples = 2, oranges = 2 etc.
I got this code from another similar question:
private function getCount(fruitArray:Array, fruitName:String):int {
var count:int=0;
for (var i:int=0; i<fruitArray.length; i++) {
if(fruitArray[i].toLowerCase()==fruitName.toLowerCase()) {
count++;
}
}
return count;
}
var fruit:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];
var appleCount=getCount(fruit, "apples"); //returns 2
var grapeCount=getCount(fruit, "grapes"); //returns 2
var orangeCount=getCount(fruit, "oranges"); //returns 2
In this code, if you want to get the count of say "apple". You need to set up variables for each item (var appleCount=getCount(fruit, "apples")). But what if you have hundreds and thousands of fruit names, it is not possible to write down new variables for each and every fruit.
I'm completely new to AS3 so forgive me. Please include clear comments in your code as I want to understand the code.
output: