DEV Community

Discussion on: How to update an array state in React.Js

 
jrishabh55 profile image
Rishabh Jain

Yeah flatMap is an option, but isn't that unnecessary ?, i mean we can use filter if we just wanna iterate over the full array.

arr.filter(it => it !== 1)

Whenever the condition returns true that item is added to the return array, and when the condition returns false it is not added to the new array. i wouldn't recommend this approach tho, same reason no need to iterate over the full array just to remove an item. Much better to use findIndex and splice combination if you don't have the index of which item to remove. with findIndex we will only iterate over an array upto the point we find the requested item.

You can't really remove an array using slice, we can do it with splice tho, it's fairly simple developer.mozilla.org/en-US/docs/W...

arr.splice(start, length) problem with react and splice is that it mutates the existing array and with react we don't wanna mutate the original state so we make a copy array first.