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?

2
  • Provide in which language you want to implement this... Commented Jul 2, 2013 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. Commented Jul 2, 2013 at 14:36

2 Answers 2

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]];
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.