2013-06-19 83 views
0

請問我該如何從數組中獲取重複值?Actionscript:從數組中選擇並顯示重複值

例: 數組[10,3,10,10]
顯示,我們有3在位置1,3和重複4

問候

我曾嘗試這一個:

q = new Array(); 
       q = [A, B, C, D]; 

       qValue = function (array) { 
       equal = array[0]; 
       for (j=0; j<array.length; j++) { 
       if (array[j]===equal) { 
       equal = array[j]; 
       } 
       } 
       return equal; 
       }; 
       trace(qValue(q)); 
+0

你嘗試過什麼嗎? – NINCOMPOOP

+0

是的,看看第一個職位 –

回答

1

像這樣的東西應該工作:

var array:Array = [1,2,3,4,3]; 

// create a dictionary and go through our array pulling out the keys 
var dict:Dictionary = new Dictionary(); 
for each(var i:int in array) 
{ 
    if(i in dict) // checks if the number is already in our dict as a key 
     dict[i]++; 
    else 
     dict[i] = 1; 
} 

// now go through our dictionary, finding the duplications 
for(var key:* in dict) 
{ 
    var num:int = dict[key]; 
    if(num == 1) 
     continue; // single value - ignore 
    trace("We have " + num + " occurrences of " + key); 
} 

編輯

也有重複值的位置(索引),而不是使用:

var array:Array = [1,2,3,4,3]; 

// create a dictionary and go through our array, pulling out the values 
var dict:Dictionary = new Dictionary(); 
var len:int   = array.length; 
for(var i:int = 0; i < len; i++) 
{ 
    var val:int = array[i]; // get the value from the array 
    if(!(val in dict)) // if it's not in our dictionary, create a new array 
     dict[val] = []; 
    dict[val].push(i); // add the index of the value to the array 
} 

// now go through our dictionary, finding the duplications 
for(var key:* in dict) 
{ 
    var indicies:Array = dict[key]; 
    if(indicies.length <= 1) 
     continue; // single value - ignore 
    trace("The value " + key + " is repeated " + indicies.length + " times. Indicies: " + indicies); 
} 

編輯 - AS2沒有 「如果」

添加的功能:

function _getArray(obj:Object, val:Number):Array 
{ 
    // try and find the one already created 
    for(var key:* in obj) 
    { 
     if(key == val) 
      return obj[val]; 
    } 

    // make a new one 
    var a:Array = []; 
    obj[val] = a; 
    return a; 
} 

您的數組循環現在應該讀取

for(var i:int = 0; i < len; i++) 
{ 
    var val:int = array[i]; // get the value from the array 
    var occurrenceArray = _getArray(obj, val); // obj = dict 
    occurrenceArray.push(i); // add the index of the value to the array 
} 
+0

謝謝,仍然在 –

+0

看到更新的重複位置prb - 我們只是用一個數組持有 – divillysausages

+0

替換計數哦哦是的這就是解決方案,非常感謝你配對:) –