【问题标题】:Rename multiple same occurrences in array重命名数组中多个相同的匹配项
【发布时间】:2013-07-02 14:32:43
【问题描述】:

我有一系列标题(句子)。其中一些标题在整个数组中重复,例如我的数组是(为清楚起见,缩短标题):

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

如您所见,有些值会重复多次。我需要通过将计数器(从 1 开始)附加到第一个匹配项来重命名多个匹配项。 所以最后我必须有:

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

这意味着我需要为每次重复事件存储计数器。

我怎么能用 javascript/jquery 写这个?

【问题讨论】:

  • 提供你想用哪种语言实现这个...
  • 您可以保留一个带有计数器的查找表,例如:{key: counter} 其中键 = 值,计数器是计数器的当前增量。

标签: javascript jquery arrays string rename


【解决方案1】:

这里有一些伪代码,其中 tally 是一个标题计数映射(例如 {title: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]];
  }
}

【讨论】:

    【解决方案2】:

    语言无关算法

    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,然后我认为一切都几乎相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多