JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Deleting an element from the state array in React

Author:JIYIK Last Updated:2025/03/17 Views:

To remove an element from the state array in React:

  1. Use filter()the method to iterate over an array.
  2. In each iteration, check whether the condition is met.
  3. Set state to the new array returned by the filter method.
import {useState} from 'react';

export default function App() {
  const initialState = [
    {id: 1, name: 'Fql', country: 'Austria'},
    {id: 2, name: 'Jiyik', country: 'China'},
  ];

  const [employees, setEmployees] = useState(initialState);

  const removeSecond = () => {
    setEmployees(current =>
      current.filter(employee => {
        // 👇️ 删除等于 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>
  );
}

Deleting an element from the state array in React

useStateWe initialize an employee status variable using the hook.

The function we pass to Array.filterthe method is called for each element in the array.

In each iteration, we check if the object's id property is not equal to 2 and return the result.

const initialState = [
  {id: 1, name: 'Fql', country: 'Austria'},
  {id: 2, name: 'Jiyik', country: 'China'},
];

const filtered = initialState.filter(obj => {
  // 👇️ 为所有 id 不等于 2 的元素返回真
  return obj.id !== 2;
});

// 👇️ [{id: 1, name: 'Fql', country: 'Austria'}]
console.log(filtered);

filterThe method returns a new array containing only those elements for which the callback function returns a true value.

If the condition is never met, Array.filterthe function returns an empty array.

We pass a function to setState, because that function is guaranteed to be called with the current (latest) state.

const removeSecond = () => {
  // 👇️ current 是当前状态数组
  setEmployees(current =>
    current.filter(employee => {
      return employee.id !== 2;
    }),
  );
};

A function is passed to when calculating the next state using the previous state setState.


Never mutate array state in React

You should not use functions like Array.pop()or Array.splice()to mutate state arrays in React.

const removeSecond = () => {
  const index = employees.findIndex(emp => emp.id === 2)

  // ⛔️ 不要这样做
  employees.splice(index, 1)

  // ⛔️ 或者这样也不好
  employees.pop()
};

State objects and arrays are immutable. In order for React to track changes, we need to set the state to a new array instead of modifying the original array.


Remove elements from the state array based on multiple conditions

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


Using the logical AND (&&) operator

The logical AND &&operator checks whether multiple conditions are true.

const initialState = [
  {id: 1, name: 'Fql', country: 'Austria'},
  {id: 2, name: 'Jiyik', country: 'China'},
  {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 evaluates to true only if both conditions are true.

The callback function returns true only if the object's id property 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 evaluates to true.

const initialState = [
  {id: 1, name: 'Fql', country: 'Austria'},
  {id: 2, name: 'Jiyik', country: 'China'},
  {id: 3, name: 'Carl', country: 'Austria'},
];

const [employees, setEmployees] = useState(initialState);

const remove = () => {
  setEmployees(current =>
    current.filter(employee => {
      return employee.name === 'Fql' || employee.name === 'Carl';
    }),
  );
};

Either of the two conditions must evaluate to a truth value for the element to be added to the new array.

In other words, if the name property of an object is equal to Fql or Carl, then the object will be added to the new array. All other objects are filtered out of the array.


Use two operators to remove elements from the state array

We can also use both operators together if we have to check multiple complex conditions.

import {useState} from 'react';

export default function App() {
  const initialState = [
    {id: 1, name: 'Fql', country: 'Austria'},
    {id: 2, name: 'Jiyik', country: 'China'},
    {id: 3, name: 'Carl', country: 'Canada'},
  ];

  const [employees, setEmployees] = useState(initialState);

  const remove = () => {
    setEmployees(current =>
      current.filter(employee => {
        return (
          (employee.name === 'Fql' ||
            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>
  );
}

Use two operators to remove elements from the state array

The code in parentheses uses the logical OR ||operator to check whether the name attribute of the employee object is one of two values.

const remove = () => {
  setEmployees(current =>
    current.filter(employee => {
      return (
        (employee.name === 'Fql' ||
          employee.name === 'Carl') &&
        employee.country === 'Canada'
      );
    }),
  );
};

If the condition is met, the logical AND &&operator checks whether the object's Country attribute is equal to Canada.

The expression in the brackets must evaluate to true and the condition on the right must evaluate to true for the object to be saved in the state array.


Remove duplicates from the State array in React

To remove duplicates from the states array:

  1. Use useState()the hook to store the array in the state.
  2. Use Set()the constructor to remove duplicates from the state array.
  3. Update the state array to the new value.
import {useState} from 'react';

const App = () => {
  const words = ['fql', 'fql', 'jiyik', 'jiyik', 'com'];
  const [state, setState] = useState(words);

  const withoutDuplicates = [...new Set(words)];

  // 👇️ ['fql', 'jiyik', '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 the State array in React

The argument we pass to the Set constructor is an iterable - in our case an array.

const words = ['fql', 'fql', 'jiyik', 'jiyik', 'com'];

// 👇️ {'fql', 'jiyik', 'com'}
console.log(new Set(words));

const withoutDuplicates = [...words];
console.log(withoutDuplicates); // 👉️ ['fql', 'jiyik', 'com']

All elements of the array are added to the newly created set. However, a Set object can only store unique values, so any duplicates are automatically removed.

...The final step is to unpack the Set values ​​into a new array using the Spread operator .


Remove duplicate objects from state array in React

To remove duplicate objects from the state array in React:

  1. Create an empty array that will store unique object IDs.
  2. Use the filter() method to iterate over the state array.
  3. Checks whether the unique ID array contains the ID of the current object.
  4. If an ID is included, the object's ID is added to the unique IDs array and the object is added to the status array.
import {useState} from 'react';

const App = () => {
  const employees = [
    {id: 1, name: 'Fql'},
    {id: 1, name: 'Fql'},
    {id: 2, name: 'Jiyik'},
    {id: 2, name: 'Jiyik'},
  ];

  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 in React

The function we pass to Array.filterthe method is called for each element (object) in the array.

const employees = [
  {id: 1, name: 'Fql'},
  {id: 1, name: 'Fql'},
  {id: 2, name: 'Jiyik'},
  {id: 2, name: 'Jiyik'},
];

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);

In each iteration, we check if the unique ID array contains the ID of the current object.

If so, we have a copy.

If it is not included, we need to add the ID to the unique ID array and return a true value from the function.

The filter method simply adds an element to the resulting array if the function passed to the method returns a true value.

uniqueEmployeesThe array does not contain any duplicates.

We use the id attribute as the identifier of the object. However, in your case, the identifier of the object might be called something else.

Essentially, our solution is:

  1. Just add unique IDs to uniqueIdsthe array.
  2. If the object's ID is not uniqueIdsin the array, the object is simply added to the result array.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to avoid cross-origin (CORS) issues in React/Next.js

Publish Date:2025/03/17 Views:166 Category:NETWORK

In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:185 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:183 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:99 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:187 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial