-->

Counting number of occurances in an Array

2019-07-12 16:37发布

问题:

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.

回答1:

    var item:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];

    //write the count number of occurrences of each string into the map {fruitName:count}
    var fruit:String;
    var map:Object = {}; //create the empty object, that will hold the values of counters for each fruit, for example map["apples"] will holds the counter for "apples"

    //iterate for each string in the array, and increase occurrence counter for this string by 1 
    for each(fruit in item)
    {
        //first encounter of fruit name, assign counter to 1
        if(!map[fruit])
            map[fruit] = 1;
        //next encounter of fruit name, just increment the counter by 1
        else
            map[fruit]++;
    }

    //iterate by the map properties to trace the results 
    for(fruit in map)
    {
        trace(fruit, "=", map[fruit]);
    }

output:

apples = 2
grapes = 2
oranges = 2