2013-07-02 22 views
1

我有一個標題(句子)的數組。一些標題重複這整個數組中,因此,例如我的陣列(簡稱爲清楚起見冠軍):重命名數組中的多個相同的事件

var arr = ['a','b', 'c', 'a', 'f', 'r', 'b', 'a']; 

正如你可以看到一些值,可重複多次。我需要通過將計數器(從1開始)附加到第一個匹配事件來重命名多個事件。 所以最後我必須有:

'a', 'a1', 'a2', 'b', 'b1' 

,這意味着我需要存儲每一個重複出現的計數器。

我怎麼能寫這在JavaScript/jQuery中?

+3

哪種語言? – dougEfresh

+0

提供你想用哪種語言實現這個... – Java

+0

你可以用一個計數器保存一個查找表,如:{key:counter}其中key =值,counter是計數器的當前增量。 – crush

回答

0

語言無關的算法

Add the elements of array to map so that no duplicate elements would be present and initialize it to 0. 
Iterate through array 
    Check if the elemnt is present in map    
    if present then                  
     map[element]++; 
     element+value of element at map+1; 
    else element 

例子:

var arr = ['a','b', 'c', 'a', 'f', 'r', 'b', 'a']; 
//initialize the map 
map m 
m[a]=0; m[b]=0; m[c]=0; m[f]=0;  m[r]=0;  

for(index=0 to size of array){ 
    if(m[arr[index]]){ 
     m[arr[index]]++; 
     write arr[index] with m[arr[index]]; 
    }else{ 
     write arr[index]; 
    } 
} 

這裏提到How to create a simple map using JavaScript/JQuery,然後我覺得一切都幾乎相同,您可以使用地圖。

1

這裏的一些僞代碼,其中帳簿是標題計數映射(例如{標題:0}):

for (var i = 0; i < arr.length; i++) { 
    if (arr.indexOf(arr[i]) != i) { 
    tally[arr[i]]++; 
    arr[i] = arr[i] + tally[arr[i]]; 
    } 
}