score:279

Accepted answer

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

score:-2

const [randomnumbers, setrandomnumbers] = usestate([111,432,321]);
const numbertobedeleted = 432;

// filter (preferred)
let newrandomnumbers = randomnumbers.filter(number => number !== numbertobedeleted)
setrandomnumbers(newrandomnumbers);

//splice (alternative)
let indexofnumbertobedeleted = randomnumbers.indexof(numbertobedeleted);
let newrandomnumbers = array.from(randomnumbers);
newrandomnumbers.splice(indexofnumbertobedeleted, 1);
setrandomnumbers(newrandomnumbers);


//slice (not preferred - code complexity)
let indexofnumbertobedeleted = randomnumbers.indexof(numbertobedeleted);
let deletednumber = randomnumbers.slice(indexofnumbertobedeleted, indexofnumbertobedeleted+1);
let newrandomnumbers = [];
for(let number of randomnumbers) {
    if(deletednumber[0] !== number)
        newrandomnumbers.push(number);
};
setrandomnumbers(newrandomnumbers);

score:-1

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

score:0

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

score:0

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

score:0

const [people, setpeople] = usestate(data);

const handleremove = (id) => {
   const newpeople = people.filter((person) => { person.id !== id;
     setpeople( newpeople );
     
   });
 };

<button onclick={() => handleremove(id)}>remove</button>

score:0

almost all the answers here seem to be for class components, here's a code that worked for me in a functional component.

const [arr,setarr]=usestate([]);
const removeelement=(id)=>{
    var index = arr.indexof(id)
    if(index!==-1){
      setarr(oldarray=>oldarray.splice(index, 1));
    }
}

score:0

just filter out deleted item and update the state with remaining items again,

let remainingitems = allitems.filter((item) => {return item.id !== item_id});
    
setitems(remainingitems);

score:1

this is your current state variable:

const [animals, setanimals] = usestate(["dogs", "cats", ...])

call this function and pass the item you would like to remove.

removeitem("dogs")

.

const removeitem = (item) => {
    setanimals((prevstate) =>
      prevstate.filter((previtem) => previtem !== item)
    );
  };

your state variable now becomes:

["cats", ...]

score:3

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.

score:17

filter method is the best way to modify the array without touching the state.

it returns a new array based on the condition.

in your case filter check the condition person.id !== id and create a new array excluding the item based on condition.

const [people, setpeople] = usestate(data);

const handleremove = (id) => {
   const newpeople = people.filter((person) => person.id !== id);

   setpeople( newpeople);
 };

<button onclick={() => handleremove(id)}>remove</button>

not advisable: but you can also use an item index for the condition if you don't have any id.

index !== itemindex

score:19

simple solution using slice without mutating the state

const [items, setitems] = usestate(data);
const removeitem = (index) => {
  setitems([
             ...items.slice(0, index),
             ...items.slice(index + 1)
           ]);
}

score:20

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

export default class postlist extends component {
  this.state = {
      postlist: [
        {
          id: 1,
          name: 'all items',
        }, {
          id: 2,
          name: 'in stock items',
        }
      ],
    }


    remove_post_on_list = (deletepostid) => {
        this.setstate({
          postlist: this.state.postlist.filter(item => item.post_id != deletepostid)
        })
      }
  
}

score:22

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[, ...]]])

var people = ["bob", "sally", "jack"]
var toremove = 'bob';
var index = people.indexof(toremove);
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.
  people.splice(index, 1);
}
console.log(people);

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

score:56

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

score:314

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

Related Query

More Query from same tag