score:279
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
})});
}
Source: stackoverflow.com
Related Query
- How to delete an item by index from a state array in React
- How to delete an item from state array?
- How to delete objects from react state hook array with a button click
- How to delete an item from state in React
- Delete item from array in state in a child component
- How to delete an object from state when it is inside an array of objects
- How to delete item in nested array to pass as react state
- How to delete item from an array by onPress event in react
- How to delete some item from redux state by some rule
- Delete multiple item from array - Redux State
- How to remove item from array stored in localstorage if the item already exists and changing state of button
- How to delete a specific item from a complex data structure while preserving the state in React-redux?
- How do I delete an Item from an array save on local storage?
- Delete an item from Redux state
- ReactJS how to delete item from list
- React JS: how to properly remove an item from this.state.data where data is an array of objects
- How do I add an item to the front of a state array in React
- How delete item from redux state?
- How to delete object from array using object property - React
- How to use useEffect hook properly with array dependency. I passed state from redux store and still my component renders infinitely
- React native delete multiple items from state array
- How can i get array of object from this data for state and count in reactjs
- Delete an Item from Array not Rendering ReactJS Hooks
- Delete element from array in redux state using a reducer in createSlice
- How to map an array of strings from react state to a select box
- How to create array from state value and setstate after removing duplicates in reactjs
- How delete an object based on its index from a nested array in React?
- how to pass the current item to the function so that i can remove it from array in react component?
- How to use an object to delete it from objects array javascript?
- In React Hooks. How to set state to a random number and use that to display a string from an array
More Query from same tag
- How to set TextField to empty string?
- Not importing class
- Zip files / folders / zips from Remote URLs with JSZip
- Next JS Global and Page Specific Share Images
- Reactstrap or React-router v4's is not redirecting for partial address link change
- How do I properly setup VS Code to debug in chrome, using an existing logged in Chrome user profile?
- Add new items to existing object model react js
- Passing Async State to Next.js Component via Prop
- Trying to reset a list before filtering, but having trouble with the asynchronous states
- Reducer running twice when using useReducer and React Context API
- Undefined prop value in child component
- Testing React click event in Jest fails because the Jquery can't be applied - How can I test it?
- How to format currency in JavaScript?
- Jest passing an object to expect().toBeCalledWith()
- How to setState while adding a key value into each array
- Wrong width for React Slick Slider in Responsive View
- Nodemon is not working: nodemon is not loading
- How to get REST API body info(JSON)?
- How can i access my json Datetime value from my react component
- Configuring next.config file
- How can I get form dynamic input data with React Js?
- draggable react divs: exponential movement
- Can I add active class when url starts a string in react Navlink?
- "TypeError: Cannot read property 'name' of undefined" error
- How can I parse the response of axios to an attribute in a React component
- Docker: Stderr:fatal error: runtime: out of memory on AWS Elasticbeanstalk
- Type 'number' is not an array type on react typescript reducer
- State use as props in component, state change will not re-render the component
- Nested Routing for React.JS
- ReactJS: clickable text - how can I disable click outside the text area?