How to exclude an element from the array if an equal value already exists?

Asked

Viewed 78 times

2

I am trying to store the ID of some accounts that have been selected by a checkbox, that is I will have an array of all accounts that are selected, but I need that when it is unchecked, delete their id from the array, i tried to make a filter with map in the array but nothing returned me, nor the console log I put to test.

const [contasSelected, setSelected] = useState([])

function cSelect(e) {
  contasSelected.map(a => {
    if (a.ID = e) {
      console.log('o ID', a.ID, 'já está marcado')
    } else {

      setSelected([...contasSelected, {
        ID: e
      }])
      console.log(contasSelected)
    }
  })
}
<tbody className='Table-Contas-Body'>
  {Contas.map( e =>(
  <tr key={ e.ID}>
    <FormCheck id={ e.ID} type="checkbox" onChange={ ()=> cSelect(e.ID)}/> // aqui é onde passo o ID da conta para a função 
      <td>{e.ID}</td>
      <td>{e.Cliente}</td>
      <td>{e.Valor}</td>
      <td>{e.DataEmissao}</td>
      <td>{e.DataVencimento}</td>
      <td>{e.Historico}</td>
  </tr>
  ))}
</tbody>

1 answer

2

1st error: you are trying to execute if (a.ID = e). But in a comparison you should use == or ===. See in What is the difference between the operators == and == in Javascript?

2nd error: the logic you are trying to apply makes no sense. The map will go through all elements of the array, one by one. And the way it is written the array will always be empty, after all you are trying to include an element in it only within the map.

Solution:

You can use the method findIndex to see if it exists and which index of the element you are looking for.

  • If not: include the element in the array.
  • If it already exists: delete the element. To do this you can create an array that is a copy of the state contasSelected, use the mercy splice to remove the desired element and then: setSelected(novoArrayQueVoceCriou).
  • 1

    Thanks for the help, I will scan my code again and do with findindex.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.