Reputation: 1933
I do not know how to check if my variable or it duplicate are already in the list before adding it.
Let's take an example of a list:
LIST = ['TestA', 'TestB', 'TestC (AZE)', 'TestB (#2)']
If I want to add 'TestA', then I add 'TestA (#2)'.
If I want to add 'TestB' or 'TestB (#X)', where X
is any number,
then I add 'TestB (#3)' because a duplicate is already present and the duplicate number will be 3.
If I want to add 'TestC (AZE)', then I add 'TestC (AZE) (#2)'.
I started doing this:
VARIABLE = "TestB"
if(this.LIST.includes(VARIABLE)) {
this.LIST.push(VARIABLE + " (#2)");
} else {
this.LIST.push(VARIABLE);
}
The problem is that if I add "TestB" several times, several "TestB (#2)" will be added.
If anyone can help me put this into practice, thank you.
Upvotes: 2
Views: 854
Reputation: 370879
Use another object to keep track of the number of times each string has occurred so far:
LIST = [];
const counts = {};
function addToList(item) {
counts[item] = (counts[item] || 0) + 1;
LIST.push(item + (counts[item] === 1 ? '' : ' (#' + counts[item] + ')'));
}
addToList('foo');
addToList('foo');
addToList('bar');
addToList('baz');
addToList('bar');
addToList('foo');
console.log(LIST);
Either make sure addToList
is not called with a (#
suffix, or strip out (#
suffixes first, eg:
LIST = [];
const counts = {};
function addToList(item) {
const trailingMatch = item.match(/ \(#\d+\)$/);
if (trailingMatch) {
item = item.slice(0, item.length - trailingMatch[0].length);
}
counts[item] = (counts[item] || 0) + 1;
LIST.push(item + (counts[item] === 1 ? '' : ' (#' + counts[item] + ')'));
}
addToList('foo');
addToList('foo');
addToList('bar');
addToList('baz');
addToList('bar');
addToList('foo');
addToList('foo (#2)');
console.log(LIST);
Upvotes: 3
Reputation: 37755
You can try something like this
2
let LIST = ['TestA', 'TestB', 'TestC (AZE)', 'TestB (#2)']
let adder = (val) => {
let key = val.replace(/^(.*)\(#\d+\)$/g, '$1').trim()
let findValue = [...LIST].reverse().find(v => v.includes(key))
if (findValue) {
let [_, digit] = (findValue.match(/^.*\s\(#(\d+)\)/) || [0, 0])
if (digit) {
LIST.push(key + ` (#${+digit+1})`)
} else {
LIST.push(key + ` (#${2})`)
}
} else {
LIST.push(val)
}
}
adder("TestA")
console.log(LIST)
adder("TestC (AZE)")
console.log(LIST)
adder("TestZ")
console.log(LIST)
adder("TestRandom (23)")
console.log(LIST)
adder("TestRandom (23)")
console.log(LIST)
Upvotes: 1