Remove a Non-Unique Item from a useState Array – React

There are a bunch of tutorials on how to remove duplicate values from an array, but what if we wanted to remove just one of those non-unique items and keep the rest? This can be relatively easy in vanilla Javascript using a simple for loop, but sometimes we need to make it inline in JSX or process it right in a useState hook. If you want to remove a non-unique item from a useState array, all you need is filter and indexOf:

const formItems = [1,2,3,3,4,4,3,8,6,6,9]
const itemToFilterOut = 3
const filteredFormItems = formItems.filter((item,index,self)=> index !== self.indexOf(itemToFilterOut))
console.log(filteredFormItems)
//[1,2,3,4,4,3,8,6,6,9]

Here, we use the item’s unique index to filter it out rather than using it’s non-unique value which would remove all instances of that value.

Jason Velarde

Jason Velarde is the guy behind STEMcadia. He has been involved with public libraries for over 15 years. Nowadays, he's spending countless hours in front of the computer as a web developer. Nearly every evening after work, you’ll find him either reverse engineering (breaking) a gadget, building prototype robots, or working on personal coding projects, but when he's not, he's here researching and writing about all things related to STEM on STEMcadia.