Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
How to remove item form array?

I have the following array in my React naitve app.

  const [items, setItems] = useState([
    { answers: [{ id: 1 }, { id: 2 }] },
    { answers: [{ id: 1 }] },
    { answers: [{ id: 1 },] },
  ]);

I want to delete item from first row with id 2 So the final should look like that

[
    { answers: [{ id: 1 }] },
    { answers: [{ id: 1 }] },
    { answers: [{ id: 1 }] },
  ]

How can i do that ? I tried to start like this

  const onDelete = useCallback((itemId) => {
    var newItems = [...items];

    newItems = newItems[0].answers.filter(....) //I don't know how to continue

    setItems(newItems);
  }, []);

Sorry for the question but I'm new to react-native and javascript!

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

Assuming that you want to change the first object and you want do dynamically filter the answers based on your itemId, the onDelete function would look like this:

  const onDelete = useCallback((itemId) => {
    setItems((prev) => [
      { answers: prev[0].answers.filter(({ id }) => id !== itemId) },
      ...prev.slice(1),
    ]);
  }, []);
about 4 years ago · Santiago Gelvez Relatório

0

I've expanded @sm3sher answer to allow removing answer ids at any index.

const onDelete = useCallback((answerId=2,itemIndex=0)=>{
  const newItems = [...items];
  let currentItem = newItems[itemIndex]
  currentItem.answers = currentItem.answers.filter(({id})=> id !== answerId)
  newItems[itemIndex] = currentItem;
  setItems(newItems);
},[]);
about 4 years ago · Santiago Gelvez Relatório

0

You should create a new object, whose answers property is the filtered original. The filter callback can be ({id}) => id != 2:

   newItems[0] = { answers: newItems[0].answers.filter(({id}) => id != 2) };
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda