David Johns
David Johns

Reputation: 1734

How to remove multiple items in an array of objects in React?

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?

Upvotes: 0

Views: 1456

Answers (2)

raphalg
raphalg

Reputation: 468

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 })
}

Upvotes: 1

Dario Fiore
Dario Fiore

Reputation: 473

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

Upvotes: 1

Related Questions