0

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?

1
  • 1
    1. filter must return true if you want to keep, and false if you want to discard. So you should return false if questionsToRemove includes your each.order 2. you should get the returned array (const filteredQuestions = questionsData.filter....) Commented Jan 26, 2021 at 13:31

2 Answers 2

1

Method .filter of Array doesn't mutate the array, it create a new array with filtered value. Just assign result of filter to questionssData.

 questionssData = questionssData.filter(each => {
      return !questionsToRemove.includes(each.order)
 });
Sign up to request clarification or add additional context in comments.

Comments

1

You have to assign the filter result array to your variable. Also in order to filter(remove), you have to return false from your method :

removeQuestion = () => {
    var questionssData = this.state.questionsData
    questionssData = questionssData.filter(each => {
        return !questionsToRemove.includes(each.order)
    });
    this.setState({ questionsData: questionssData })
}

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.