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?
CodePudding user response:
You can use a javascript set.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.
CodePudding user response:
Instead of for loop use javascript filter option to check whether the element already exist. So that you could restrict the user from making the duplicate entry.
CodePudding user response:
newArray.value = [...new Set [numArray?.value]]
CodePudding user response:
before pushing any value into your array, I would verify if the "value" that's being added is already in the array.
var existingValue = numArray.find(item => item === numberValue.value)
if (existingValue) {
window.alert('No Duplicates Allowed!');
return;
}
numArray.value.push(numberValue.value);
If the value does not exist then we can proceed pushing into array
CodePudding user response:
The submit function's logic is wrong. For example, debug it by steps as below.
enter '5', after
submit()
,numArray = ['5']
,newArray = ['5']
enter '5', after
submit()
,numArray = ['5', '5']
,newArray = ['5']
,window.alert()
called.enter '2',
numArray = ['5', '5', '2']
, after fisrtfor
loop,newArray = ['5']
, after second loop,window.alert()
called becausenumArray[1]
is '5' also.
So you need to do numArray = newArray.concat()
after sumbit()
to make numArray
undunplicated. Otherwise it will trigger alert on all subsequent inputs.