[javascript] Delete item from state array in react

The story is, I should be able to put Bob, Sally and Jack into a box. I can also remove either from the box. When removed, no slot is left.

people = ["Bob", "Sally", "Jack"]

I now need to remove, say, "Bob". The new array would be:

["Sally", "Jack"]

Here is my react component:

...

getInitialState: function() {
  return{
    people: [],
  }
},

selectPeople(e){
  this.setState({people: this.state.people.concat([e.target.value])})
},

removePeople(e){
  var array = this.state.people;
  var index = array.indexOf(e.target.value); // Let's say it's Bob.
  delete array[index];
},

...

Here I show you a minimal code as there is more to it (onClick etc). The key part is to delete, remove, destroy "Bob" from the array but removePeople() is not working when called. Any ideas? I was looking at this but I might be doing something wrong since I'm using React.

This question is related to javascript arrays reactjs

The answer is


I also had a same requirement to delete an element from array which is in state.

const array= [...this.state.selectedOption]
const found= array.findIndex(x=>x.index===k)
if(found !== -1){
   this.setState({
   selectedOption:array.filter(x => x.index !== k)
    })
 }

First I copied the elements into an array. Then checked whether the element exist in the array or not. Then only I have deleted the element from the state using the filter option.


It's Very Simple First You Define a value

state = {
  checked_Array: []
}

Now,

fun(index) {
  var checked = this.state.checked_Array;
  var values = checked.indexOf(index)
  checked.splice(values, 1);
  this.setState({checked_Array: checked});
  console.log(this.state.checked_Array)
}

removePeople(e){
    var array = this.state.people;
    var index = array.indexOf(e.target.value); // Let's say it's Bob.
    array.splice(index,1);
}

Redfer doc for more info


Easy Way To Delete Item From state array in react:

when any data delete from database and update list without API calling that time you pass deleted id to this function and this function remove deleted recored from list

_x000D_
_x000D_
export default class PostList extends Component {_x000D_
  this.state = {_x000D_
      postList: [_x000D_
        {_x000D_
          id: 1,_x000D_
          name: 'All Items',_x000D_
        }, {_x000D_
          id: 2,_x000D_
          name: 'In Stock Items',_x000D_
        }_x000D_
      ],_x000D_
    }_x000D_
_x000D_
_x000D_
    remove_post_on_list = (deletePostId) => {_x000D_
        this.setState({_x000D_
          postList: this.state.postList.filter(item => item.post_id != deletePostId)_x000D_
        })_x000D_
      }_x000D_
  _x000D_
}
_x000D_
_x000D_
_x000D_


const [people, setPeople] = useState(data);

const handleRemove = (id) => {
   const newPeople = people.filter((person) => { person.id !== id;
     setPeople( newPeople );
     
   });
 };

<button onClick={() => handleRemove(id)}>Remove</button>

Use .splice to remove item from array. Using delete, indexes of the array will not be altered but the value of specific index will be undefined

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

Syntax: array.splice(start, deleteCount[, item1[, item2[, ...]]])

_x000D_
_x000D_
var people = ["Bob", "Sally", "Jack"]_x000D_
var toRemove = 'Bob';_x000D_
var index = people.indexOf(toRemove);_x000D_
if (index > -1) { //Make sure item is present in the array, without if condition, -n indexes will be considered from the end of the array._x000D_
  people.splice(index, 1);_x000D_
}_x000D_
console.log(people);
_x000D_
_x000D_
_x000D_

Edit:

As pointed out by justin-grant, As a rule of thumb, Never mutate this.state directly, as calling setState() afterward may replace the mutation you made. Treat this.state as if it were immutable.

The alternative is, create copies of the objects in this.state and manipulate the copies, assigning them back using setState(). Array#map, Array#filter etc. could be used.

this.setState({people: this.state.people.filter(item => item !== e.target.value);});

const array = [...this.state.people];
array.splice(i, 1);
this.setState({people: 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.


When using React, you should never mutate the state directly. If an object (or Array, which is an object too) is changed, you should create a new copy.

Others have suggested using Array.prototype.splice(), but that method mutates the Array, so it's better not to use splice() with React.

Easiest to use Array.prototype.filter() to create a new array:

removePeople(e) {
    this.setState({people: this.state.people.filter(function(person) { 
        return person !== e.target.value 
    })});
}

Here is a minor variation on Aleksandr Petrov's response using ES6

removePeople(e) {
    let filteredArray = this.state.people.filter(item => item !== e.target.value)
    this.setState({people: filteredArray});
}

You forgot to use setState. Example:

removePeople(e){
  var array = this.state.people;
  var index = array.indexOf(e.target.value); // Let's say it's Bob.
  delete array[index];
  this.setState({
    people: array
  })
},

But it's better to use filter because it does not mutate array. Example:

removePeople(e){
  var array = this.state.people.filter(function(item) {
    return item !== e.target.value
  });
  this.setState({
    people: array
  })
},

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release