1

I'm trying to create a button so that when clicked, a specific element stored in an associative array will get deleted. But what I've done doesn't seem to work. Any help will be appreciated.

  // Creates the button
  bodyText = bodyText + '<input type="button" id="btnDeleteQuestion" 
  value="Delete a question">';

  document.getElementById("btnDeleteQuestion")
    .addEventListener("click", function() {
      // Deletes the third question stored in the questionBank
      delete questionBank[2]['questionText'];
      console.log(questionBank);  
    });
}
vZeqk_
  • 23
  • 6

2 Answers2

1

Use splice (if it is an array) to remove the element from the array.

questionBank.splice(2, 1); // from the third element, remove 1 item.

What you have written in your question will get the questionBank[2] and then delete a property called questionText in the object.

It will also throw an error if the array does not have at least 3 items or if the 3rd item is null or undefined

vader
  • 889
  • 8
  • 22
0

I hope you helpful this

var questionBank= ["questionText", "questionText1", "questionText2"];
document.getElementById("btnDeleteQuestion").addEventListener("click", function() {
    // index get by text         
    const index = questionBank.indexOf("questionText");   
    if(index!=-1){  
         //Delete element by index
          questionBank.splice(index, 1);
    }
    console.log(questionBank);  
});
Udara Kasun
  • 2,182
  • 18
  • 25