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.
Related
How would you find the first item matching a certain criteria in a nested array, and stop once found?
In a 1D array, this is what the Array.find function is for, but how would you do it for a 2D array, and, even neater, for n-dimension array?
Also, I'm trying to come up with a neat solution using es6 and array functions such as find, map, reduce etc, rather than using more traditional loops and variables to maintain state (see one such old-school solution below).
The data may look something like this
const data = [
{arr: [{val:6,name:'aaa'},{val:4,name:'bbb'},{val:8,name:'ccc'}]},
{arr: [{val:3,name:'mmm'},{val:5,name:'nnn'},{val:9,name:'ppp'},{val:5,name:'ooo'}]}
]
I'm hoping I can do something similar to array.find (and its predicate / testing function), but I need to go deeper and find eg the first item with val=5. For the data above, I'd expect to get the item with name 'nnn' (not 'ooo'), and have the process end once the first item is found. Similar to Array.find, I want to avoid processing the rest of the data once a matching item is found.
One boring old way to do it would be something like this, with a loop, but that's... boring, and not as neat as the lovely array functions :)
let found
// loop through all data entries in the outer array
for (const d of data) {
// attempt to find a matching item in the inner array.
// using array.find means we stop at the first match, yay!
const theItem = d.arr.find(item => {
return myPredicate(item)
})
// we also need to break out of the loop. ugh!
if (theItem) {
found = theItem
break
}
}
// return what we found (may be undefined)
return found
Now, I realise that I can do something with find() and some(), say, similar to the answer here ES6 - Finding data in nested arrays, but the problem is that using find on the outer array means that we get back the first item of the outer data array, whereas I want an item from the inner arr array.
const outer = data.find(d => {
return d.arr.some(item => {
return myPredicate(item)
})
})
I would then have to process outer AGAIN to find the item in outer.arr, something like
outer.arr.find(item => myPredicate(item))
This doesn't sit well with me, as the call to some(...) has already gone through and found the matching inner item!
I thought this would be straight forward, and maybe it is, but for one reason or another I got stuck on this little challenge.
I've also looked at the nice traverse library (https://www.npmjs.com/package/traverse), but again that seems to be more about traversing through a whole tree rather than stopping and returning once a particular node is found.
Anyone up for a challenge? ;)
The easiest (though slightly ugly) solution would be to assign the matching item to an outer variable when found:
let foundNested;
data.some(subarr => (
subarr.some((item) => {
if (myPredicate(item)) {
foundNested = item;
return true;
}
});
});
You might use .reduce to avoid assigning to an outer variable:
const myPredicate = ({ val }) => val === 5;
const data = [
{arr: [{val:6,name:'aaa'},{val:4,name:'bbb'},{val:8,name:'ccc'}]},
{arr: [{val:3,name:'mmm'},{val:5,name:'nnn'},{val:9,name:'ppp'},{val:5,name:'ooo'}]}
];
const found = data.reduce((a, { arr }) => (
a ||
arr.find(myPredicate)
), null);
console.log(found);
Problem is, the reduce won't short-circuit - it'll fully iterate over the outer array regardless. For true short-circuiting, I think I'd prefer using a for..of loop:
const data = [
{arr: [{val:6,name:'aaa'},{val:4,name:'bbb'},{val:8,name:'ccc'}]},
{arr: [{val:3,name:'mmm'},{val:5,name:'nnn'},{val:9,name:'ppp'},{val:5,name:'ooo'}]}
];
function findNested(outerArr, myPredicate) {
for (const { arr } of outerArr) {
for (const item of arr) {
if (myPredicate(item)) {
return item;
}
}
}
}
const myPredicate = ({ val }) => val === 5;
console.log(findNested(data, myPredicate));
You'll want to write your own find function that doesn't take a predicate but a result-producing callback:
function find(iterable, callback) {
for (const value of iterable) {
const result = callback(value);
if (result !== undefined)
return result;
}
}
With that, you can write
const data = [
{arr: [{val:6,name:'aaa'},{val:4,name:'bbb'},{val:8,name:'ccc'}]},
{arr: [{val:3,name:'mmm'},{val:5,name:'nnn'},{val:9,name:'ppp'},{val:5,name:'ooo'}]}
];
console.log(find(data, ({arr}) => find(arr, o => o.val == 5 ? o : undefined)));
Alternatively, if you want to get all results, flatMap is the perfect tool:
data.flatMap(({arr}) => arr.filter(({val}) => val == 5));
Sure, why not. I'm up for it. This can probably be improved upon. But this will work. Let's say you are trying to find an object with id of 5 in a multidimensional array.
const arr = [[[{id: 1}], [{id: 2}]], [[{id: 3}]], [[{id: 4}], [{id: 5}], [{id: 6}]]]
function findObject (obj) {
if (Array.isArray(obj)) {
const len = obj.length
for (let i = 0; i < len; i++) {
const found = findObject(obj[i])
if (found) {
return found
}
}
} else if (obj.id === 5) { // Put your search condition here.
return obj
}
}
const obj = findObject(arr)
console.log('obj: ', obj)
This seems to work, but, in my opinion, it's still not clean with that 'found' variable sitting outside the main block and being assigned from inside the nested find block. It's better though. Thoughts?
let found
data.find(d =>
d.arr.find(item => {
found = myPredicate(item) ? item : void 0
return found !== void 0
}) !== void 0
)
return found
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)
}))
}
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.
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 ;
})
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.