1

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);
  }
}
2
  • 1
    I'm not very familiar with the splice method. You can have a look here MDN documentation. Commented May 20, 2022 at 10:01
  • Is selectedSports a state? Commented May 20, 2022 at 10:09

3 Answers 3

1

You can remove elements that are equal to sport from the array using:

selectedSports = selectedSports.filter(x => x != sport)
Sign up to request clarification or add additional context in comments.

Comments

0

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");

Comments

0

const a = ['sport', 'sport1', 'sport2', 'sport3', 'sport3'];
const b = a.filter(x => x != 'sport');
console.log(b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.