I'm currently in the process of creating a demo using Vue that prevents users from adding duplicate items to an array. The user interacts with the following text field and button:
<div>
<input v-model="numberValue" type="number" />
</div>
<div>
<button @click="submit" type="submit">Submit</button>
</div>
Once I push numberValue.value
into the numArray
array, I use a for
loop to iterate over the items in numArray. Then, I utilize the indexOf
method within a conditional statement to check for existing occurrences of array items in newArray. If the array item is not already present in newArray, it gets added.
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 tried setting up an else if
statement to detect when the user tries to input a duplicate array item. In this condition, I included a window alert to notify the user about entering a duplicate. However, after entering a duplicate value, the alert pops up on all subsequent inputs, even ones that are unique. How can I correctly configure the else if statement to target duplicates and only display an alert for those cases?