1

I have an array of titles (sentences). Some of these titles repeat in this whole array, so for example my array is (shortened titles for clarity):

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

As you can see some values repeat more than once. I need to rename multiple occurrences by appending the counter (starting from 1) to the first matching occurrence. So in the end I must have:

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

which means I need to have counter stored for every of the repeating occurrence.

How could I write this in javascript/jquery?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Toniq
  • 4,492
  • 12
  • 50
  • 109
  • Provide in which language you want to implement this... – Java Jul 02 '13 at 14:34
  • You could keep a lookup table with a counter like: `{key: counter}` where key = the value, and counter is the current increment of the counter. – crush Jul 02 '13 at 14:36

2 Answers2

1

Here's some pseudocode, wherein tally is a title-count mapping (e.g. {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]];
  }
}
0

Language agnostic algorithm

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

Example:

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];
     }
}

You could use maps as mentioned here How to create a simple map using JavaScript/JQuery and then I think everything is almost same.

Community
  • 1
  • 1
ritesh
  • 907
  • 3
  • 11
  • 31