2014-06-30 6 views
0

배열에서 가장 일반적인 값을 찾는 방법을 찾고 싶습니다. 따라서 "데이터"라는 벨로우즈 배열에서 "1"의 10 가지 값을가집니다. 어떻게하면이 정보를 추출하여이 정보를 찾기가 어려울 지 알 수 있습니다. 어떤 도움을 주시면 감사하겠습니다!AS3 배열에서 가장 일반적인 값 찾기

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"; 

답변

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; 
}     
+0

WOW 정말 감사를! 완벽하게 작동 .. 아주 좋아! – sputn1k