Remove an Element from state Array in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
6 min

banner

# Table of Contents

  1. Remove an element from state Array in React
  2. Never mutate the state array in place in React
  3. Remove elements from a state array based on multiple conditions
  4. Remove the Duplicates from a State array in React
  5. Remove the duplicate objects from a state array in React

# Remove an element from state Array in React

To remove an element from a state array in React:

  1. Use the filter() method to iterate over the array.
  2. On each iteration, check if a condition is met.
  3. Set the state to the new array that the filter method returned.
App.js
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> ); }

react remove object from state array

The code for this article is available on GitHub

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.

App.js
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.

App.js
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.

# Never mutate the state array in place in React

You should never use functions like Array.pop() or Array.splice() to mutate the state array in React.

App.js
const removeSecond = () => { const index = employees.findIndex(emp => emp.id === 2) // โ›”๏ธ Don't do this employees.splice(index, 1) // โ›”๏ธ Or this employees.pop() };
The code for this article is available on GitHub

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.

# Remove elements from a state array based on multiple conditions

If you need to remove an object from a state array based on multiple conditions, use the logical AND (&&) or logical OR (||) operators.

# Using the logical AND (&&) operator

The logical AND (&&) operator checks if multiple conditions are true.

App.js
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 code for this article is available on GitHub

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.

# Using the logical OR (||) operator

The logical OR (||) operator checks if at least one of the conditions evaluate to true.

App.js
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'; }), ); };
The code for this article is available on GitHub

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.

# Using both operators to remove an element from a state array

You can also use both operators if you have to check for multiple, complex conditions.

App.js
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> ); }

remove from state array based on multiple conditions

The code for this article is available on GitHub

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.

App.js
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.

# Remove the duplicates from a State array in React

To remove the duplicates from a state array:

  1. Use the useState() hook to store the array in the state.
  2. Use the Set() constructor to remove the duplicates from the state array.
  3. Update the state array to the new value.
App.js
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;

remove duplicates from state array

The code for this article is available on GitHub

The parameter we passed to the Set constructor is an iterable - in our case an array.

App.js
const words = ['bobby', 'bobby', 'hadz', 'hadz', 'com']; // ๐Ÿ‘‡๏ธ {'bobby', 'hadz', 'com'} console.log(new Set(words)); const withoutDuplicates = [...words]; console.log(withoutDuplicates); // ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com']
All of the elements of the array get added to the newly created 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.

# Remove the duplicate objects from a state array in React

To remove the duplicate objects from a state array:

  1. Create an empty array that will store the unique object IDs.
  2. Use the filter() method to iterate over the state array.
  3. Check if the unique IDs array contains the ID of the current object.
  4. If the ID is contained, add the object's ID to the unique IDs array and the object to the state array.
App.js
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;

remove duplicate objects from state array

The code for this article is available on GitHub

The function we passed to the Array.filter() method gets called with each element (object) in the array.

App.js
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.

The 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:

  1. Only add unique IDs to the uniqueIds array.
  2. Only add the object to the results array if the object's ID is not in the uniqueIds array.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev