I have an array of state which is controlled through a dropdown.
This is state held like:
const [finalselected, setfinalSelected] = useState([]);
When a submit button is clicked, I would like to confirm that an element does not already exist in the array, for example an individual cannot input "experience": "A similar role" 10 times into the array.
My current function does not stop additional elements coming if it is a duplicate:
const onSubmitFinalSelection = (val) => {
if (!finalselected.includes(selectedExperience)) {
//if finalselected does NOT include the element, then add in a new element
// setfinalSelected((prev) => [...prev, selectedExperience, inputfield]);
setfinalSelected((prevFinalSelection) => [
...prevFinalSelection,
{
//this is the dropdown
experience: selectedExperience,
//this is an input
inputfield,
},
]);
}
console.log(finalselected)
};
How would you re-write this?
CodePudding user response:
Something like this? I don't think the includes
function works with the selectedExperience as single parameter since the array contains objects.
const onSubmitFinalSelection = (val) => {
// If found, return
if (finalselected.some(x => x.experience === selectedExperience))
return;
setfinalSelected([...finalSelected, {
//this is the dropdown
experience: selectedExperience,
//this is an input
inputfield,
}])
console.log(finalsSlected)
};
CodePudding user response:
Alerting if the element is already inside my array if not doing normal push.
let selectedValues = document.querySelector(".selectedValues");
let array = [];
function myFunction(option) {
option = option.value;
if (array.includes(option)) {
alert(option " " "is already selected")
} else {
array.push(option);
}
selectedValues.textContent = array;
}
<textarea type="text"></textarea>
<select onchange="myFunction(this)" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>