Last updated: Apr 7, 2024
Reading timeยท6 min
To remove an element from a state array in React:
filter()
method to iterate over the array.filter
method returned.import {useState} from 'react'; export default function App() { const initialState = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bobby Hadz', country: 'Belgium'}, ]; const [employees, setEmployees] = useState(initialState); const removeSecond = () => { setEmployees(current => current.filter(employee => { // ๐๏ธ Remove the object that has an id equal to 2 return employee.id !== 2; }), ); }; return ( <div> <button onClick={removeSecond}>Remove second</button> {employees.map(({id, name, country}) => { return ( <div key={id}> <h2>name: {name}</h2> <h2>country: {country}</h2> <hr /> </div> ); })} </div> ); }
We initialized an employees
state variable using the
useState hook.
The function we passed to the Array.filter() method gets called with each element in the array.
On each iteration, we check if the id
property of the object is not equal to
2
and return the result.
const initialState = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bobby Hadz', country: 'Belgium'}, ]; const filtered = initialState.filter(obj => { // ๐๏ธ Returns truthy for all elements that // Don't have an `id` equal to 2 return obj.id !== 2; }); // ๐๏ธ [{id: 1, name: 'Alice', country: 'Austria'}] console.log(filtered);
The filter
method returns a new array containing only the elements for which
the callback function returned a truthy value.
If the condition is never met, the Array.filter
function returns an
empty array.
We passed a function to setState
because the function is guaranteed to be
invoked with the current (most up-to-date) state.
const removeSecond = () => { // ๐๏ธ current is the current state array setEmployees(current => current.filter(employee => { return employee.id !== 2; }), ); };
When the next state is computed using the previous state, pass a function to
setState
.
You should never use functions like Array.pop()
or Array.splice()
to mutate
the state array in React.
const removeSecond = () => { const index = employees.findIndex(emp => emp.id === 2) // โ๏ธ Don't do this employees.splice(index, 1) // โ๏ธ Or this employees.pop() };
State objects and arrays are immutable. In order for React to keep track of changes, we need to set the state to a new array, rather than modifying the original array.
If you need to remove an object from a state array based on multiple conditions, use the logical AND (&&) or logical OR (||) operators.
The logical AND (&&) operator checks if multiple conditions are true
.
const initialState = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bobby Hadz', country: 'Belgium'}, {id: 3, name: 'Carl', country: 'Austria'}, ]; const [employees, setEmployees] = useState(initialState); const remove = () => { setEmployees(current => current.filter(employee => { return employee.id !== 3 && employee.id !== 2; }), ); };
The logical AND (&&) operator only evaluates to true
if both conditions are
true
.
The callback function returns true
only if the id
property of the object is
not equal to 3
and not equal to 2
.
The logical OR (||) operator checks if at least one of the conditions evaluate
to true
.
const initialState = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bobby Hadz', country: 'Belgium'}, {id: 3, name: 'Carl', country: 'Austria'}, ]; const [employees, setEmployees] = useState(initialState); const remove = () => { setEmployees(current => current.filter(employee => { return employee.name === 'Alice' || employee.name === 'Carl'; }), ); };
Either of the 2 conditions has to evaluate to a truthy value for the element to be added to the new array.
In other words, if the name
property on the object is equal to Alice
or
equal to Carl
, the object will be added to the new array. All other objects
are filtered out from the array.
I've also written an article on how to remove a key from a state object.
You can also use both operators if you have to check for multiple, complex conditions.
import {useState} from 'react'; export default function App() { const initialState = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bobby Hadz', country: 'Belgium'}, {id: 3, name: 'Carl', country: 'Canada'}, ]; const [employees, setEmployees] = useState(initialState); const remove = () => { setEmployees(current => current.filter(employee => { return ( (employee.name === 'Alice' || employee.name === 'Carl') && employee.country === 'Canada' ); }), ); }; return ( <div> <button onClick={remove}>Remove second</button> {employees.map(({id, name, country}) => { return ( <div key={id}> <h2>name: {name}</h2> <h2>country: {country}</h2> <hr /> </div> ); })} </div> ); }
The code in the parentheses uses the logical OR (||) operator to check if the
name
property of the employee
object is one of two values.
const remove = () => { setEmployees(current => current.filter(employee => { return ( (employee.name === 'Alice' || employee.name === 'Carl') && employee.country === 'Canada' ); }), ); };
If the condition is met, the logical AND (&&) operator checks if the country
property on the object is equal to Canada
.
The expression in the parentheses has to evaluate to true
and the condition on
the right-hand side has to evaluate to true
for the object to be kept in the
state array.
If you need to remove a key from a state object, click on the link and follow the instructions.
To remove the duplicates from a state array:
useState()
hook to store the array in the state.Set()
constructor to remove the duplicates from the state array.import {useState} from 'react'; const App = () => { const words = ['bobby', 'bobby', 'hadz', 'hadz', 'com']; const [state, setState] = useState(words); const withoutDuplicates = [...new Set(words)]; // ๐๏ธ ['bobby', 'hadz', 'com'] console.log(withoutDuplicates); const removeDuplicates = () => { setState(prevState => [...new Set(prevState)]); }; return ( <div> <button onClick={removeDuplicates}> Remove duplicates </button> {state.map((word, index) => { return ( <div key={index}> <h2>{word}</h2> </div> ); })} </div> ); }; export default App;
The parameter we passed to the Set constructor is an iterable - in our case an array.
const words = ['bobby', 'bobby', 'hadz', 'hadz', 'com']; // ๐๏ธ {'bobby', 'hadz', 'com'} console.log(new Set(words)); const withoutDuplicates = [...words]; console.log(withoutDuplicates); // ๐๏ธ ['bobby', 'hadz', 'com']
Set
. However, the Set
object can only store unique values, so all duplicates get automatically removed.The last step is to use the Spread operator (...) to unpack the values of the Set into a new array.
If you get the warning prop spreading is forbidden, click on the link and follow the instructions.
To remove the duplicate objects from a state array:
filter()
method to iterate over the state array.import {useState} from 'react'; const App = () => { const employees = [ {id: 1, name: 'Alice'}, {id: 1, name: 'Alice'}, {id: 2, name: 'Bobby Hadz'}, {id: 2, name: 'Bobby Hadz'}, ]; const [state, setState] = useState(employees); const handleClick = () => { const uniqueIds = []; setState(currentState => { return currentState.filter(element => { const isDuplicate = uniqueIds.includes(element.id); if (!isDuplicate) { uniqueIds.push(element.id); return true; } return false; }); }); }; return ( <div> <button onClick={handleClick}> Remove duplicate objects </button> {state.map((employee, index) => { return ( <div key={index}> <h2>id: {employee.id}</h2> <h2>name: {employee.name}</h2> </div> ); })} </div> ); }; export default App;
The function we passed to the Array.filter() method gets called with each element (object) in the array.
const employees = [ {id: 1, name: 'Alice'}, {id: 1, name: 'Alice'}, {id: 2, name: 'Bobby Hadz'}, {id: 2, name: 'Bobby Hadz'}, ]; const uniqueIds = []; const uniqueEmployees = employees.filter(element => { const isDuplicate = uniqueIds.includes(element.id); if (!isDuplicate) { uniqueIds.push(element.id); return true; } return false; }); console.log(uniqueEmployees);
On each iteration, we check if the unique IDs array contains the ID of the current object.
If it does, we have a duplicate.
If it doesn't contain it, we need to add the ID to the unique IDs array and return a truthy value from the function.
filter
method only adds an element to the results array if the function passed to the method returns a truthy value.The uniqueEmployees
array doesn't contain any duplicates.
We used the id
property as the object's identifier. However, in your case the
object's identifier might be called something else.
In essence, our solution is to:
uniqueIds
array.uniqueIds
array.