Deleting a particular element from an array - javascript

state = { filters: ['all'] }
this.state.filters.includes('humans') ?
this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown)
I'm using a condition such that, when I click on a button the item('humans') gets pushed to state and when I click on the same button again I need to remove the item('humans') from the array. Push is working fine, I need help in removing it. I used filter like the above code , it does not get added again to the array but also not removing.
Thanks in advance.

Use:
let index = this.state.filters.indexOf('humans');
if (index !== -1)
this.state.filters.splice(index, 1);
Or you better follow this approach to avoid mutating the state in React:
let array = [...this.state.filters]; // make a separate copy of the array
let index = array.indexOf('humans')
if (index === -1) { // not in the array
array.push('humans');
this.setState({filters: array});
} else { // exists in the array
array.splice(index, 1);
this.setState({filters: array});
}

To remove an element from array, You can do below thing
filters.splice(index_of_the_val, 1);

You shouldn't modify the state with the push, 'cause it might not trigger the re-rendering. You should use the setState method.
toggleFilter = filter => {
const isIncluded = this.state.filters.includes(filter)
const add = (filters, filter) =>
filters.concat(filter)
const remove = (filters, filter) =>
filters.filter(f => f !== filter)
this.setState(prevState => ({
filters: isIncluded
? remove(prevState.filters, filter)
: add(prevState.filters, filter)
}))
}

Related

React - Deleting rest of the array instead of just one item

Here's the link:
https://codesandbox.io/s/heuristic-heisenberg-9cxb9
I have this method: deleteItem
This code:
return {
monsters: prevState.monsters
.slice(0, deleteItemPosition)
.concat(
prevState.monsters.slice(
deleteItemPosition + 1,
prevState.monsters.length
)
)
};
This is the code I use to remove an item from array on position deleteItemPosition, because I can't use monsters.splice(deleteItemPosition, 1) because of immutability.
So why does my monsters array get cut off from deleteItemPosition to the end?
Try it yourself, entering some number 0-5 into "index to delete"
If I update line
let deleteItemPosition = this.state.deleteItemPosition;
and I hardcode it to, let say
let deleteItemPosition = 3;
Then I notice the item on position 3 gets removed, as I wanted.
Your deleteItem function could be simplified like this, also makes sure that no state updates are skipped:
deleteItem = () => {
this.setState(prevState => {
return { monsters: prevState.monsters.filter((_, i) => i !== +prevState.deleteItemPosition)};
})
};
The functional update is recommended as your new state(new monsters array) depends on the previous state.
Update:
You can use destructuring to avoid using prevState all the time. And you need to convert the deleteItemPosition to a number because the input's value is a string.
deleteItem = () => {
this.setState(({monsters, deleteItemPosition}) => {
return { monsters: monsters.filter((_, i) => i !== +deleteItemPosition)};
})
};
Just make a shallow copy of the monsters array, apply Array.prototype.splice method for deleting your item and return the copied monsters array.
const copyMonsters = [...prevState.monsters];
copyMonsters.splice(deleteItemPosition, 1);
return {
monsters: copyMonsters
}
Put this code inside the setState function in your case.

How to setState to update an array in React?

I need to update an array in the state of my component in React.
I've seens several topic with this question, but so far all of them are adding new items to the array with the spread operator, but I need to add OR remove items on a callback like this:
handleCheck (newStatus, isChecked) {
this.setState({ filterStatus: [...this.state.filterStatus, newStatus] })
}
But the problem here is that it didn't work for status where the isChecked boolean comes false to remove them from the array
What is the best way to add or remove items from that array, hopefully with spread operator?
Thanks
try to use the .filter to remove the element. Remember to duplicate the array (using [...array] syntax) before using .filter, to don't change the original array:
handleCheck (newStatus, isChecked) {
let newArray = isChecked? // if isChecked is true
[...this.state.filterStatus, newStatus] : // add element
[...this.state.filterStatus].filter(e => e !== newStatus); // remove the elements that are equal to newStatus
this.setState({ filterStatus: newArray})
}
Think it functionnal !
const prevArray = this.state.array;
const itemsToAdd = [item, item, item];
//this function map the prev array escaping elements to remove
//and then push itemsToAdd to the new array
const updateArray = ( i = [0], newArray = [] ) =>
i < prevArray ?
yourRemovingCondition(prevArray[i]) ?
updateArray( i + 1, newArray )
: updateArray( i + 1, [...newArray, prevArray[i])
: [...newArray, ...itemsToAdd]
;
setState({array: updateArray()];
Put the check, add the element only when the bool isChecked is true, otherwise use filter to remove the element from the array.
Like this:
handleCheck (newStatus, isChecked) {
this.setState(prevState => {
let filterStatus;
if (isChecked) {
filterStatus = [...prevState.filterStatus, newStatus];
} else {
filterStatus = prevState.filterStatus.filter(el => el.id !== newStatus.id)
}
return { filterStatus }
})
}
Note: In place of id in filter callback method use the correct unique property name.

Need to remove the delItem from the toDos array not sure how

I can't figure out how to complete this function. I have filtered through to find the variable that matches the id but now I need to match that item to the delItem var and delete it.
function deleteToDo(tot) {
let delItem = toDos.filter((remove) => remove.id === tot);
/// i need to remove item from toDos array that matches delItem.
renderTheUI(toDos);
}
Array#filter returns an array, with all items that match the predicate. Instead of getting the item that you want to remove, get an array without the item by checking that the id is not equal to tot. Then use the filtered array in renderTheUI:
function deleteToDo(tot) {
const filteredToDos = toDos.filter((item) => item.id !== tot);
renderTheUI(filteredToDos);
}
I would suggest moving the call to renderTheUI out of the deleteToDo method, since it might be very confusing. The deleteToDo will return an updated array, and then you can render the new array:
function deleteToDo(tot) {
return toDos.filter((item) => item.id !== tot);
}
const filteredToDos = deleteToDo(2);
renderTheUI(filteredToDos);
You do not need to find the element with filter but its index in the array.
function deleteToDo(tot) {
let delIndex = toDos.findIndex((remove) => remove.id === tot);
if (delIndex !== -1){ // if element was found
toDos.splice(delIndex,1); // remove the element from the toDos array
}
renderTheUI(toDos);
}

Swapping two objects in array: ReactJS

I asked myself if there is a clean, proper way to swap two objects in an array using setState. This is what I currently do:
export function moveStepUp(index) {
if(index > 0){
let currentStep = this.state.stepsData[index];
let stepAbove = this.state.stepsData[index - 1];
this.setState((prevState) => ({
stepsData: prevState.stepsData.map((step, i) => {
if(i === index - 1)
return {
...currentStep,
position: i
};
if(i === index)
return {
...stepAbove,
position: i
};
return step;
})
}), () => console.log(this.state.stepsData));
}
}
This code is working, but I thought there might be a better solution. It seems like too much lines of code for such a simple task. Thanks!
Why not simply swapping two array values by using a third variable if you know the element index.
First copy the array in another variable, swap two array values, then use setState to update the state value.
Like this:
this.setState(prevState => {
let data = [...prevState.data];
let temp = data[index-1];
data[index-1] = data[index];
data[index] = temp;
return { data };
})
Instead of spread operator, you can use any other way to create a copy of array.
In react hooks
you can use this, this works for me
const [array,setArray]= useState([]);
setArray(array => {
let data = [...array];
let temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
console.log(data);
return data ;
})

How to remove an object from an array in Immutable?

Given a state like this:
state = {
things: [
{ id: 'a1', name: 'thing 1' },
{ id: 'a2', name: 'thing 2' },
],
};
How can I create a new state where ID "a1" is removed? It's easy enough to push new items:
return state.set(state.get('things').push(newThing));
But I can't figure out how to search for and remove an object by its id property. I tried this:
return state.set('tracks',
state.get('tracks').delete(
state.get('tracks').findIndex(x => x.get('id') === 'a2')
)
)
But it seems messy, plus it only works if the item is found, because if findIndex returns -1, that's a valid value for delete.
You can use Array#filter.
return state.set('things', state.get('things').filter(o => o.get('id') !== 'a1'));
When you are using filter it iterates all cycle -> one effective way is finding index => slice and using splitter ...
const index = state.findIndex(data => data.id === action.id);
return [...state.slice(0, index), ...state.slice(index + 1)];
Alternatively, as you are "searching and then deleting"...
var itemIndex = this.state.get("tracks").findIndex(x => x.get('id') === 'a2');
return itemIndex > -1 ? this.state.deleteIn(["tracks", itemIndex]) : this.state;
This will ensure the state is not mutated when there are no changes.
Found this thread while looking for a solution to a similar task.
Solved it with update method:
return state.update('things', (things) => things.filter((t) => t.id !== action.things.id))
any idea/comment which one is better/preferred?
You can do that even without immutable.js with following function.
function arrayFilter(array, filter) {
let ret = array
let removed = 0
for (let index = 0; index < array.length; index++) {
const passed = filter(array[index], index, array)
if (!passed) {
ret = [...ret.slice(0, index - removed), ...ret.slice(index - removed + 1)]
removed++
}
}
return ret
}
ImmutableJS working with nested arrays
Immutablejs is great but at the same time makes things more complicated in some edge cases, particularly when working with nested arrays.
Sometimes it is easier to take it back to JS in a general sense for this particular issue.
// 1. get a copy of the list into normal JavaScript
const myList = state.getIn(['root', 'someMap', 'myList']).toJS()
// 2. remove item in list using normal JavaScript and/or anything else
myList.splice(deleteIndex, 1)
// 3. return the new state based on mutated myList
return state
.mergeDeep({ root: { someMap: { myList: undefined } }})
.mergeDeep({ root: { someMap: { myList } }})
Unfortunately, step 3 is necessary to specifically set to undefined because if you simply set myList directly as an array value, ImmutableJS will do a comparison of values between the current list and only modify them creating strange behavior.
The justification for this is to simplify the mental overhead. I do not recommend doing this in a loop, rather manipulate the pure JS array in a loop if you must but should be prior to step 3.

Categories

Resources