Renaming duplicates in a JavaScript array

advertisements

I am asking for help to solve the problem renaming the strings in array that looks like this:

["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"]

After the function execution it should look as follows:

["a(1)","a(6)","a","a(2)","a(3)","a(4)","a(5)","a(7)","a(8)","a(9)","a(10)","a(11)"]

Empty array and array free of duplicates should left untouched.

My idea is to populate an empty object with key/value pairs and then just push them to a new array:

function renameFiles(arr){
    var itemsObj = {};
    var count = 1;
    for (var i = 0; i < arr.length; i++){

        itemsObj[arr[i]] = count;
        // if the key present, rename the array item and add it to the
        // itemsObj
        if (arr[i] in itemsObj){
            itemsObj[arr[i] + '(' + (i - (i - 1)) + ')']
        }

    }
    console.log(itemsObj)
    // once the itmesObj is set, run the loop and push the keys to the
    // array
    return arr;

}

var array = ["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"]
renameFiles(array);

The problem is that the itemsObj is not get populated with duplicates keys. There should be some other method that can handle this task. I am a beginner and probably not aware of that method.


You're almost there. You'd keep a count, and check for duplicates, and then do another check for duplicates with parentheses, and update the count appropriately

function renameFiles(arr){
  var count = {};
  arr.forEach(function(x,i) {

    if ( arr.indexOf(x) !== i ) {
      var c = x in count ? count[x] = count[x] + 1 : count[x] = 1;
      var j = c + 1;
      var k = x + '(' + j + ')';

      while( arr.indexOf(k) !== -1 ) k = x + '(' + (++j) + ')';
      arr[i] = k;
    }
  });
  return arr;
}

var res = renameFiles(["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"]);
console.log(res)
.as-console-wrapper {top:0; max-height:100%!important}