Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add and delete values in an Array in React?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading