close

How to delete an item from state array?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to delete an item from state array? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to delete an item from state array ?

  1. How to delete an item from state array ?

    to delete an item from state array Some answers mentioned using 'splice', which did as Chance Smith said mutated the array. I would suggest you to use the Method call 'slice' (Document for 'slice' is here) which make a copy of the original array.

  2. How to delete an item from state array ?

    to delete an item from state array Some answers mentioned using 'splice', which did as Chance Smith said mutated the array. I would suggest you to use the Method call 'slice' (Document for 'slice' is here) which make a copy of the original array.

Method 1

To remove an element from an array, just do:

array.splice(index, 1);

In your case:

removePeople(e) {
  var array = [...this.state.people]; // make a separate copy of the array
  var index = array.indexOf(e.target.value)
  if (index !== -1) {
    array.splice(index, 1);
    this.setState({people: array});
  }
},

Method 2

Some answers mentioned using ‘splice’, which did as Chance Smith said mutated the array. I would suggest you to use the Method call ‘slice’ (Document for ‘slice’ is here) which make a copy of the original array.

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment