Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda