I often have to check if an item is part of an array. If it is, I would like to remove it. If it’s not, then it should be added. Essentially its toggling the existence of a given item in the array.
const onDateSelected = function (date) {
const inArray = selectedDates.value.find((d) => d === date) !== undefined;
if (inArray) {
selectedDates = selectedDates.filter((d) => d !== date);
} else {
selectedDates.push(date);
}
};
Is there a shorter / quicker way to do this?
2
Answers
You can try this :
Using a
Set
makes this a lot easier usinghas
,delete
andadd
:If you really need an array, consider using
indexOf
combined withsplice