AS3查找数组中最常见的值

时间:2014-06-30 16:36:03

标签: arrays actionscript-3 flash

我想找到一种方法来找到一个数组中最常见的值,所以在下面的数组中称为"数据"它有10个值" 1"。我如何能够提取这些信息,发现很难找到任何相关信息。任何帮助,将不胜感激!

var data:Array = ["1","1","1","1","1","1","1","1","1","2","2","one","two","five","six","1","2","one","two","three","four","five","2","one","two","three","four","five","2","five","2","one","two","five","six","2","one","two","five","six","2","one","two","five","six"];

results = "1";

1 个答案:

答案 0 :(得分:3)

这可能不是最有效的方式,但它确实可以解决问题:

function mostCommonValue(array:Array):Object
{
    // create a dictionary of each unique item in the array and its count     
    var dict:Dictionary = new Dictionary(true);
    for each(var element:Object in array)
    {
        if(!dict[element]){
            dict[element] = 0;
        }
        dict[element]++;
    }

    var max:Number = 0;
    var mostCommon:Object;
    // loop over each item in the dictionary to find the highest number of occurrences 
    for(var key:Object in dict)
    {
        if(dict[key] > max){
            max = dict[key];
            mostCommon = key;
        }
    }

    return mostCommon;
}