Quentin
Quentin

Reputation: 1933

How to add a string to a list without duplicates

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)']

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

Answers (2)

CertainPerformance
CertainPerformance

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

Code Maniac
Code Maniac

Reputation: 37755

You can try something like this

  • Get the key from the passed value to be added,
  • Reverse the list and find the first occurrence of matching key
  • Get the digit out of key, if digit is present add 1 to it else set it as 2
  • If key is not find add the value itself to list

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

Related Questions