I need to take an array of names, remove any names that are only numbers, and if there is a duplicate name then add an incrementing number to the end of that string. Example in code below does this but only up to the third entry. After that it continues as 'test2' or 'trick2' when it should be 'test3' and 'trick3'.
const deviceNames = ['test', 'trick', '4', 'test', 'trick', '8', 'test', 'trick', 'test', 'trick']
const deviceNameSystem = (deviceNames) => {
let arr = [];
deviceNames.map((item)=>{
let counter = 1
arr.includes(item + counter) ? counter++ && arr.push(item + counter):
arr.includes(item) ? arr.push(item + counter):
arr.push(item)
})
console.log(arr.filter(x => isNaN(x)));
}
deviceNameSystem(deviceNames)
Outputs [ 'test', 'trick', 'test1', 'trick1', 'test2', 'trick2', 'test2', 'trick2' ]
const deviceNames = ['test', 'trick', '4', 'test', 'trick', '8', 'test', 'trick', 'test', 'trick']
var nameHash = {}
var newList = [];
deviceNames.foreach(name => {
if(name == parseInt(name))
return;
if(!nameHash[name]) {
nameHash[name] = 1;
newList.push(name);
} else {
newList.push(name + nameHash[name]);
nameHash[name]++;
}
});