javascriptvue.jsfor-loopvuejs3indexof

how to remove duplicate array elements in JavaScript and Vue


I am attempting to set up a Vue demo that prevents a user from inputting duplicate items in an array. The inputs values with the following text field and button:

 <div>
    <input v-model="numberValue" type="number" />
 </div>
 <div>
   <button @click="submit" type="submit">Submit</button>
</div>

After pushing numberValue.value into the numArray array, I then for to loop through the items in numArray. Then, I used the indexOf method in a conditional to check for occurances of array items in newArray. If array items don't already exist in newArray, then they will be pushed into newArray.

const submit = () => {
  numArray.value.push(numberValue.value)
  
  newArray.value = [];
  
  for (let i = 0; i < numArray.value.length; i++) { 
    if(newArray.value.indexOf(numArray.value[i]) === -1) { 
        newArray.value.push(numArray.value[i]); 
        console.log(newArray.value)
    } else if (newArray.value.indexOf(numArray.value[i]) !== -1) {
      window.alert('No Duplicates Allowed!')
    }
  }
}

I then attempted to set up an else if statement that targets instances when the user tries to input a duplicate array item. On the else if, I added a window.alert to alert the user when entering a duplicate. After entering a duplicate, I see the alert. I then see the alert on all subsequent inputs, even ones that are not duplicates. How can I go about properly setting up the else if statement to target duplicates and trigger an alert?


Solution

  • You can easily achieve this requirement by comparing the input value with indexOf and lastIndexOf values in a numArray. And to have non-duplicate values you can use Set.

    Working Demo :

    new Vue({
      el: '#app',
      data: {
        numberValue: null,
        numArray: []
      },
      methods: {
        submit() {
          this.numArray.push(this.numberValue);
          if (this.numArray.indexOf(this.numberValue) !== this.numArray.lastIndexOf(this.numberValue)) {
            alert('No Duplicates Allowed!');
          }
          this.numArray = [...new Set(this.numArray)]
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <input v-model="numberValue" type="number" />
      <button @click="submit" type="submit">Submit</button>
      <br><br>
      {{ numArray }}
    </div>