When I add an item to the array it works but the splice does not.
const handleSportsFollowed = async (sport) => {
if (selectedSports.includes(sport)) {
selectedSports.splice(sport, 1);
alert("Removed");
} else {
selectedSports.push(sport);
}
}
You can remove elements that are equal to sport from the array using:
selectedSports = selectedSports.filter(x => x != sport)
const a = ['sport', 'sport1', 'sport2', 'sport3', 'sport3'];
const b = a.filter(x => x != 'sport');
console.log(b);
You need to find the index for splice. Check Document how splice work
const handleSportsFollowed = async (sport) => {
if (selectedSports.includes(sport)) {
selectedSports.splice(selectedSports.indexOf(sport), 1);
console.log("if selectedSports ", selectedSports);
} else {
selectedSports.push(sport);
console.log("else selectedSports", selectedSports);
}
Working example
const selectedSports = ['Jan', 'March', 'April', 'June'];
const testFun = (sport) => {
if (selectedSports.includes(sport)) {
selectedSports.splice(selectedSports.indexOf(sport), 1);
console.log("selectedSports ", selectedSports);
} else {
selectedSports.push(sport);
console.log("selectedSports", selectedSports);
}
}
testFun("March");