2

here is a link to my code https://codesandbox.io/s/strange-bash-0n1bf?file=/src/components/TagEditor.vue I have created a tag input with vue js here I am adding new item by input entry I want to prevent duplicate tag name

addTag (name) {
    if ( this.tags.length < 6 )  {
      this.tags.push({
      id: String(Math.floor(Math.random() * 9)),
      name,
      })
      this.name = ""
    }
  },

hope someone could help me with it

rozhan
  • 321
  • 1
  • 3
  • 12
  • 1
    You can use the `includes()` function to see if there is a duplicate: https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript – AlexSp3 Jul 31 '21 at 23:28

1 Answers1

2

You can map your tags object array to an array containing only the string names and see if the name is already in use, if this is the case ignore the entry (might still want to clear the input field)


    addTag(name) {
      if(this.tags.map(e => e.name).includes(name)) {
        return;
      }
      if (this.tags.length < 6) {
        this.tags.push({
          id: String(Math.floor(Math.random() * 999999999)),
          name,
        });
        this.name = "";
      }
    },

Codesandbox

LeeLenalee
  • 27,463
  • 6
  • 45
  • 69