I have a React app with an array of Objects. I use a method to first, get a list of object ids and then remove the elements in the array by comparing them to the ids list. The problem is, the function produces the wrong output.
This is the function
var questionsToRemove = [3,5,6,7];
state.questionsData = [
{ order: 1, question: "q1" },
{ order: 2, question: "q2" },
{ order: 3, question: "q3" },
{ order: 4, question: "q4" },
{ order: 5, question: "q5" },
{ order: 6, question: "q6" },
{ order: 7, question: "q7" },
];
removeQuestion = () => {
var questionssData = this.state.questionsData
questionssData.forEach(each => {
if (questionsToRemove.includes(each.order)) {
questionssData.splice(questionssData.indexOf(each))
}
});
this.setState({ questionsData: questionssData })
}
The above method produces wrong output as
{ order: 1, question: "q1" },
{ order: 2, question: "q2" },
{ order: 4, question: "q4" },
{ order: 6, question: "q6" },
I tried the ES6 filter method as follows
removeQuestion = () => {
var questionssData = this.state.questionsData
questionssData.filter(each => {
return questionsToRemove.includes(each.order)
});
this.setState({ questionsData: questionssData })
}
But this produces the same original array without filtering anything. How can I remove the selected objects from the array?
const filteredQuestions = questionsData.filter....)