The idea of the following script is to iterate an array and as it detects that an element is similar to another, regardless of its index, indicate with the number 2 that it is repeated. In the event that there are 3 equals, that 2 becomes 3 . So on with each similarity found. If another element is repeated, the same. For example, if an array like this is passed to the program: ['Sun', 'Moon', 'Sun', 'Asteroid', 'Sun', 'Moon'], the object to be returned and displayed on the console should be ['Sun', 'Moon', 'Sun2', 'Asteroid', 'Sun3', 'Moon2']. I am trying with this code, but it would not be working:
let contador = 2;
const nuevoArreglo = arr => {
return arr.map((val, index) => {
return arr.indexOf(val) !== index ? `${val}${contador++}` : val;
})
};
Here is what appears on the screen:
Note : Those values are pushed to an array and then the function takes care of returning the new object.
I create an array of strings
I create a counter which is an object literal to store the values of the array arr as a key
This to have the following format
The idea is to be modifying each key of the literal object.
I create a new array with map considering the literal object, if the key does not exist in the literal object I define it and start at 0.
full code