how to delete an item from state array?

  • Last Update :
  • Techknowledgy :

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. 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. 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

This is our Splunktool team suggestion ✌, we tried and its working fine
const handleRemove = (removeIndex) => {
   setValue(oldArray => {
      return oldArray.filter((value, i) => i !== removeIndex)
   })
}

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

To remove an element from an array, just do:

array.splice(index, 1);

Suggestion : 2

To remove an item from a state array in React, call the filter() method on the array, specifying a test that every item in the array apart from the one to be removed will pass, then update the state with the result of filter() with setState. State is meant to be immutable in React, so we can’t update the array by mutating it. It has to be replaced with a new array returned from filter() for the view to update. By combining the filter() method with the && operator, we are able to specify a compound boolean expression that removes the fruit objects with ids of 2 and 4.

1._
import { useState } from 'react';

export default function App() {
  const initialState = [
    { id: 1, name: 'Banana', amount: 5 },
    { id: 2, name: 'Apple', amount: 6 },
  ];

  const removeSecond = () => {
    setFruits((current) =>
      current.filter((fruit) => fruit.id !== 2)
    );
  };

  const [fruits, setFruits] = useState(initialState);

  return (
    <div style={{ margin: '16px' }}>
      <button onClick={removeSecond}>Remove second</button>
      {fruits.map((fruit) => (
        <div key={fruit.id}>
          <h2>Name: {fruit.name}</h2>
          <h2>Amount: {fruit.amount}</h2>
          <hr />
        </div>
      ))}
    </div>
  );
}

We remove the fruit object with the id 2 by returning a condition from the filter() callback that is true only for the items in the array that don’t have an id of 2. Doing this excludes the target item from the array returned from filter().

const initialState = [{
      id: 1,
      name: 'Banana',
      amount: 5
   },
   {
      id: 2,
      name: 'Apple',
      amount: 6
   },
];

const secondRemoved = initialState.filter((fruit) => fruit.id !== 2);

// [ { id: 1, name: 'Banana', amount: 5 } ]
console.log(secondRemoved);

Since App here is a functional component, we use the useState() React hook to create the initial state array. The first value useState() returns lets us access the state data. The second value is a function used to update the state (generically called setState). We pass a function to setState (named setFruits here) to ensure that we get the current/latest state.

const removeSecond = () => {
   // "current" contains the latest state array
   setFruits((current) =>
      current.filter((fruit) => fruit.id !== 2)
   );
};

Here is an example of using the logical OR (||) operator to remove an item from a state array.

const initialState = [{
      id: 1,
      name: 'Banana',
      amount: 5
   },
   {
      id: 2,
      name: 'Apple',
      amount: 6
   },
   {
      id: 3,
      name: 'Orange',
      amount: 10
   },
   {
      id: 4,
      name: 'Watermelon',
      amount: 1
   },
];

const [fruits, setFruits] = useState(initialState);

const remove = () => {
   setFruits((current) =>
      current.filter(
         (fruit) =>
         fruit.name === 'Orange' || fruit.name === 'Apple'
      )
   );
};

Here is an example of using the logical AND (&&) operator to remove an item from a state array:

const initialState = [{
      id: 1,
      name: 'Banana',
      amount: 5
   },
   {
      id: 2,
      name: 'Apple',
      amount: 6
   },
   {
      id: 3,
      name: 'Orange',
      amount: 10
   },
   {
      id: 4,
      name: 'Watermelon',
      amount: 1
   },
];

const [fruits, setFruits] = useState(initialState);

const remove = () => {
   setFruits((current) =>
      current.filter(
         (fruit) => fruit.id !== 2 && fruit.id !== 4
      )
   );
};

Suggestion : 3

Use the filter() method to iterate over the array. To remove an object from a state array in React: On each iteration, we check if the id property of the object is not equal to 2 and return the result. If you need to remove an object from a state array based on multiple conditions, use the logical AND (&&) or logical OR (||) operators.

1._
Copied!import {useState} from 'react';

export default function App() {
  const initialState = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
  ];

  const [employees, setEmployees] = useState(initialState);

  const removeSecond = () => {
    setEmployees(current =>
      current.filter(employee => {
        // πŸ‘‡οΈ remove object that has id equal to 2
        return employee.id !== 2;
      }),
    );
  };

  return (
    <div>
      <button onClick={removeSecond}>Remove second</button>

      {employees.map(({id, name, country}) => {
        return (
          <div key={id}>
            <h2>name: {name}</h2>
            <h2>country: {country}</h2>

            <hr />
          </div>
        );
      })}
    </div>
  );
}
2._
Copied!
   const initialState = [{
         id: 1,
         name: 'Alice',
         country: 'Austria'
      },
      {
         id: 2,
         name: 'Bob',
         country: 'Belgium'
      },
   ];

const filtered = initialState.filter(obj => {
   // πŸ‘‡οΈ returns truthy for all elements that
   // don't have an id equal to 2
   return obj.id !== 2;
});

// πŸ‘‡οΈ [{id: 1, name: 'Alice', country: 'Austria'}]
console.log(filtered);
3._
Copied!
   const removeSecond = () => {
      // πŸ‘‡οΈ current is the current state array
      setEmployees(current =>
         current.filter(employee => {
            return employee.id !== 2;
         }),
      );
   };
5._
Copied!
   const initialState = [{
         id: 1,
         name: 'Alice',
         country: 'Austria'
      },
      {
         id: 2,
         name: 'Bob',
         country: 'Belgium'
      },
      {
         id: 3,
         name: 'Carl',
         country: 'Austria'
      },
   ];

const [employees, setEmployees] = useState(initialState);

const remove = () => {
   setEmployees(current =>
      current.filter(employee => {
         return employee.name === 'Alice' || employee.name === 'Carl';
      }),
   );
};

Suggestion : 4

To remove an element from a state array in React: Use the filter() method to iterate over the array. The function we passed to the Array.filter method will get called with each element in the array. If you need to remove an element from a state array based on multiple conditions, use the logical AND (&&) or logical OR (||) operators.

1._
Copied!import {useState} from 'react';

export default function App() {
  // πŸ‘‡οΈ primitives array
  const [names, setNames] = useState(['Alice', 'Bob']);

  const removePrimitiveFromArray = () => {
    // βœ… remove 'Bob' from array
    setNames(current =>
      current.filter(element => {
        return element !== 'Bob';
      }),
    );
  };

  const initialState = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
  ];

  // πŸ‘‡οΈ array of objects
  const [employees, setEmployees] = useState(initialState);

  const removeObjectFromArray = () => {
    // βœ… Remove object with id 2 from array
    setEmployees(current =>
      current.filter(obj => {
        return obj.id !== 2;
      }),
    );
  };

  return (
    <div>
      <button onClick={removePrimitiveFromArray}>
        Remove string from state array
      </button>

      {names.map((element, index) => {
        return <h2 key={index}>{element}</h2>;
      })}

      <hr />
      <br />

      <button onClick={removeObjectFromArray}>
        Remove object from state array
      </button>

      {employees.map(employee => {
        return (
          <div key={employee.id}>
            <h2>name: {employee.name}</h2>
            <h2>country: {employee.country}</h2>

            <hr />
          </div>
        );
      })}
    </div>
  );
}
2._
Copied!
   const names = ['Alice', 'Bob'];

const result = names.filter(element => {
   return element !== 'Bob';
});

// πŸ‘‡οΈ ['Alice']
console.log(result);

// ---------------------------------------------

const employees = [{
      id: 1,
      name: 'Alice',
      country: 'Austria'
   },
   {
      id: 2,
      name: 'Bob',
      country: 'Belgium'
   },
];

const result2 = employees.filter(obj => {
   return obj.id !== 2;
});

// πŸ‘‡οΈ [{id: 1, name: 'Alice', country: 'Austria'}]
console.log(result2);
3._
Copied!setNames(current =>
   current.filter(element => {
      return element !== 'Bob';
   }),
);

setEmployees(current =>
   current.filter(obj => {
      return obj.id !== 2;
   }),
);
5._
Copied!
   const initialState = [{
         id: 1,
         name: 'Alice',
         country: 'Austria'
      },
      {
         id: 2,
         name: 'Bob',
         country: 'Belgium'
      },
      {
         id: 3,
         name: 'Carl',
         country: 'Austria'
      },
   ];

const [employees, setEmployees] = useState(initialState);

const remove = () => {
   setEmployees(current =>
      current.filter(employee => {
         return employee.name === 'Alice' || employee.name === 'Carl';
      }),
   );
};

Suggestion : 5

The delete button exists on the <Item/> component. However, the state which holds the list of <Item/>’s on the page is in the component. Therefore, if we want to modify that state (remove an item from the array), it should be done in that component itself. How do we do that? By raising an event, then handling that event. Let’s see a diagram. The component that owns the state, should be the one modifying it. Now, in the </Item> component, we can accept the data carried by the props object and use it to initialize the state of the <Item/> component!

Another key point regarding props is that it is read only. If you try to break this rule by doing something like this.

handleIncrement = e => {
   this.props.value = 1;
   this.setState({
      count: this.state.count + 1
   });
};
2._
import React, { Component } from "react";

class Item extends Component {
  state = {
    count: this.props.value
  };

  handleIncrement = e => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <React.Fragment>
        <div className="card mb-2">
          <h5 className={this.styleCardHeader()}>{this.styleCount()}</h5>
          <div className="card-body">
            <button
              onClick={item => {
                this.handleIncrement({ item });
              }}
              className="btn btn-lg btn-outline-secondary"
            >
              Increment
            </button>

            <button className="btn btn-lg btn-outline-danger ml-4">
              Delete
            </button>
          </div>
        </div>
      </React.Fragment>
    );
  }

  styleCardHeader() {
    let classes = "card-header h4 text-white bg-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  styleCount() {
    const { count } = this.state;
    return count === 0 ? "No Items!" : count;
  }
}

export default Item;

This is a pretty cool concept. We are going to create the event handler in <Items/> and then pass a reference to it via props to <Item/>. First, we can define a simple handleDelete() function.

items.jsx

import React, { Component } from "react";
import Item from "./item";

class Items extends Component {
  state = {
    items: [{ id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 0 }]
  };

  handleDelete = () => {
    alert("Button Clicked!");
  };

  render() {
    return (
      <React.Fragment>
        {this.state.items.map(item => (
          <Item 
          key={item.id} 
          value={item.value} 
          onDelete={this.handleDelete} 
          />
        ))}
      </React.Fragment>
    );
  }
}

export default Items;

In the child component, we need to pass the id of the item we want to delete to the parent. Otherwise, React will have no idea which item to delete. As we reviewed before, here is the way to pass an argument using an arrow function.

item.jsx

import React, { Component } from "react";

class Item extends Component {
  state = {
    count: this.props.value
  };

  handleIncrement = e => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <React.Fragment>
        <div className="card mb-2">
          <h5 className={this.styleCardHeader()}>{this.styleCount()}</h5>
          <div className="card-body">
            <button
              onClick={item => {
                this.handleIncrement({ item });
              }}
              className="btn btn-lg btn-outline-secondary"
            >
              Increment
            </button>

            <button
              onClick={() => this.props.onDelete(this.props.id)}
              className="btn btn-lg btn-outline-danger ml-4"
            >
              Delete
            </button>
          </div>
        </div>
      </React.Fragment>
    );
  }

  styleCardHeader() {
    let classes = "card-header h4 text-white bg-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  styleCount() {
    const { count } = this.state;
    return count === 0 ? "No Items!" : count;
  }
}

export default Item;

Now in the parent component, we need to update the handleDelete() function to accept that id as a parameter. In addition, we need to use the filter function to create a new array of items which does not contain the item which was clicked. Then we have to call the setState() function to update the state.

items.jsx

import React, { Component } from "react";
import Item from "./item";

class Items extends Component {
  state = {
    items: [{ id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 0 }]
  };

  handleDelete = itemId => {
    const items = this.state.items.filter(item => item.id !== itemId);
    this.setState({ items: items });
  };

  render() {
    return (
      <React.Fragment>
        {this.state.items.map(item => (
          <Item
            key={item.id}
            value={item.value}
            onDelete={this.handleDelete}
            id={item.id}
          />
        ))}
      </React.Fragment>
    );
  }
}

export default Items;

Suggestion : 6

We can remove an element by its index by setting the new state for the array as follows: We filter the products array to delete the first member and we set the result as the new state using the callback argument of the setProductsArray() method. We use React's useState hook to define a state array named productsArray for our products. In the callback of the state setter function, we may return a new array to update a React component's state array. As an example, consider the following:

1._
const [productsArray, setProductsArray] = useState([]);
2._
setProductsArray((products) => products.filter((_, index) => index !== 0));
3._
const removeProduct = (index) => {
   setProductsArray([
      ...products.slice(0, index),
      ...products.slice(index + 1, products.length)
   ]);
}

Suggestion : 7

My favorite way of deleting is deleting by id, followed by the index. Let me know which is your favorite in the comments below πŸ‘‡. If you have an array of objects and you want to delete them based on the id of the object, you can do so by using the following code: If you think you can have duplicate values and you want to delete them by the array index, you can achieve it in a similar fashion. Have you started working on React recently and wanted to know the right way to delete an item from an array stored in the useState hook? You are at the right place!

1._
npx create - react - app react - delete - usestate
2._
body {
   display: flex;
   justify - content: center;
}

ul {
   list - style - type: none;
   padding: 0;
}
li {
   padding: 6 px 0;
   display: flex;
   justify - content: space - between;
}

button {
   margin - left: 20 px;
}
3._
import { useState } from "react"

function App() {
  const [fruits, setFruits] = useState([
    "🍎 Apple",
    "🍊 Orange",
    "🍌 Banana",
    "πŸ‡ Grapes",
  ])
  return (
    <div className="App">
      <ul>
        {fruits.map(fruit => {
          return (
            <li key={fruit}>
              <span>{fruit}</span>
              <button>Delete</button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default App
5._
import { useState } from "react"

function App() {
  const [fruits, setFruits] = useState([
    "🍎 Apple",
    "🍊 Orange",
    "🍌 Banana",
    "πŸ‡ Grapes",
  ])
  const deleteByIndex = index => {
    setFruits(oldValues => {
      return oldValues.filter((_, i) => i !== index)
    })
  }
  return (
    <div className="App">
      <ul>
        {fruits.map((fruit, index) => {
          return (
            <li key={fruit}>
              <span>{fruit}</span>
              <button onClick={() => deleteByIndex(index)}>Delete</button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default App
6._
import { useState } from "react"

function App() {
  const [fruits, setFruits] = useState([
    { id: 1, name: "🍎 Apple" },
    { id: 2, name: "🍊 Orange" },
    { id: 3, name: "🍌 Banana" },
    { id: 4, name: "πŸ‡ Grapes" },
  ])
  const deleteById = id => {
    setFruits(oldValues => {
      return oldValues.filter(fruit => fruit.id !== id)
    })
  }
  return (
    <div className="App">
      <ul>
        {fruits.map(fruit => {
          return (
            <li key={fruit.id}>
              <span>{fruit.name}</span>
              <button onClick={() => deleteById(fruit.id)}>Delete</button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default App

Suggestion : 8

Learn to Code Interactive Courses, where you Learn by writing Code. GO Language JavaScript CSS HTML Interactive Courses, where you Learn by writing Code. Practice SQL Query in browser with sample Dataset. Run C programs and code examples online.

1._
people = ["Bob", "Sally", "Jack"]
2._
["Sally", "Jack"]
3._
...

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

   ...
5._
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
      });
   }
},
6._
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)
      })
   }

}

Suggestion : 9

Answer: Use the splice() Method You can use the splice() method to remove the item from an array at specific index in JavaScript. The syntax for removing array elements can be given with splice(startIndex, deleteCount) . There are different methods and techniques you can use to remove elements from JavaScript arrays: To remove an object from an array by its value: Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.25-Jul-2022

In this post, we will examine how to solve the How To Delete Element At A Particular Index Of Array In React Js problem using examples from the programming language.

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

Suggestion : 10

shift – Removes from the beginning of an Array. pop – Removes from the End of an Array. To remove a property from all objects in an array: Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.25-Jul-2022 In this session, we will try our hand at solving the How To Remove An Object From Array In React Native puzzle by using the computer language. The following piece of code will demonstrate this point.

In this session, we will try our hand at solving the How To Remove An Object From Array In React Native puzzle by using the computer language. The following piece of code will demonstrate this point.

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
// ["a", "b", "d", "e", "f"]