Home > front end >  How to add and delete values in an Array in React?
How to add and delete values in an Array in React?

Time:03-01

I am fetching records from an API. I am storing the total number of records in size.

const [size, setSize] = useState();
  let array = [];

  const handleChange = (id) => {

    for (let i = 0; i < 1; i  ) {

      for (let j = 0; j < size; j  ) {
        if(array[j] === id) {
          array.splice(j, 1);
        }
        else {
          array[j] = id;
          break;
        }
      }
    }
  };

There are checkboxes, when I click on any of the checkbox it's corresponding ID passes in the handleChange(). I am passing the id in the handleChange() to store it in an array. Also when I deselect a selected checkbox, the same ID is passed again and in the loop it checks, whether it is present or not, if it is present, it needs to be deleted from the array. I have written the logic in the above given code, but it is not working.

Can anyone please help me with the solution?

CodePudding user response:

Below is a simple way to do this;

let array = [];
const handleChange = (id) => {
    if (array.includes(id)){
        array = array.filter(ids => ids!=id)
    } else {
        array.push(id);
    }
}
  • Related