actionscript 3 - Counting number of occurances in an Array -


i want count number of occurances in array in actionscript 3.0. have

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

how can make show number of matching strings? instance, result: apples = 2, oranges = 2 etc.

i got code similar question:

    private function getcount(fruitarray:array, fruitname:string):int {     var count:int=0;     (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 code, if want count of "apple". need set variables each item (var applecount=getcount(fruit, "apples")). if have hundreds , thousands of fruit names, not possible write down new variables each , every fruit.

i'm new as3 forgive me. please include clear comments in code want understand code.

    var item:array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];      //write count number of occurrences of each string map {fruitname:count}     var fruit:string;     var map:object = {}; //create empty object, hold values of counters each fruit, example map["apples"] holds counter "apples"      //iterate each string in array, , increase occurrence counter string 1      each(fruit in item)     {         //first encounter of fruit name, assign counter 1         if(!map[fruit])             map[fruit] = 1;         //next encounter of fruit name, increment counter 1         else             map[fruit]++;     }      //iterate map properties trace results      for(fruit in map)     {         trace(fruit, "=", map[fruit]);     } 

output:

apples = 2 grapes = 2 oranges = 2 

Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -