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?