我想找到一种方法找到一个数组中最常见的值,所以波纹管阵列称为数据,在它的1,10个值。如何将我能够提取这些信息发现很难找到这方面的消息。任何帮助,将AP preciated!
VAR数据:数组= ["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"];
结果=1;
解决方案
这可能不是最有效的方式,但它肯定是卓有成效的:
函数mostCommonValue(数组:数组):对象
{
//阵列和计数在创建每个独特项目的字典
VAR字典:字典=新词典(真正的);
每个(VAR元素:数组对象)
{
如果(!字典[元]){
字典[元] = 0;
}
字典[元] ++;
}
VAR最大:数= 0;
VAR mostCommon:对象;
//循环遍历字典中的每一个项目,以找到最高出现次数
对于(VAR键:在字典的对象)
{
如果(字典[关键]>最大){
最大=字典[关键];
mostCommon =键;
}
}
返回mostCommon;
}
i would like to find a way to find the most common value in an Array, so in the bellow array called "data" it has 10 values of "1". how would i be able to extract this information finding it hard to find any information on this. any help would be appreciated!
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";
解决方案
This may not be the most efficient way, but it certainly does the trick:
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;
}