How to delete an item from state array?

JavascriptArraysReactjs

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

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", ...]

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

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

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSylarView Question on Stackoverflow
Solution 1 - JavascriptiaretigaView Answer on Stackoverflow
Solution 2 - JavascriptMarcoSView Answer on Stackoverflow
Solution 3 - JavascriptDmitryView Answer on Stackoverflow
Solution 4 - JavascriptRayonView Answer on Stackoverflow
Solution 5 - JavascriptANKIT DETROJAView Answer on Stackoverflow
Solution 6 - JavascriptwillmazView Answer on Stackoverflow
Solution 7 - JavascriptHidayt RahmanView Answer on Stackoverflow
Solution 8 - JavascriptArthur ChenView Answer on Stackoverflow
Solution 9 - JavascriptAmer NMView Answer on Stackoverflow
Solution 10 - JavascriptGibbsView Answer on Stackoverflow
Solution 11 - JavascriptQC innodelView Answer on Stackoverflow
Solution 12 - JavascriptGloverView Answer on Stackoverflow
Solution 13 - JavascriptShardul BirjeView Answer on Stackoverflow
Solution 14 - JavascriptAfraz AhmadView Answer on Stackoverflow
Solution 15 - JavascriptAleksandr PetrovView Answer on Stackoverflow
Solution 16 - JavascriptRitwik MathView Answer on Stackoverflow