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

213
Vistas
How to stop adding duplicate data to Array in react.js

I followed the approach as the answer in this question suggested The issue is that I want to construct an Array using setState and I dont; want to add duplicate data.

here is the sample data

const data = [
  {
    parentId: '1',
    userChoice: 'NO',
    child: []
  },
  {
    parentId: '2',
    userChoice: 'NO',
    child: []
  },
}

I'm catching the parentId from question.id from user input. If there is the same question then I don't want to concat into the array.

This is how I'm trying.

const [data, setData] = useState([]) // state

function arrayHandler(question) {
    const hasParentId = data.find((parentId) => question.id === parentId)
    // concat if array do not have any question with same id. 
    if (!hasParentId) {
      setData((data) => data.concat({ parentId: question.id, userChoice: 'NO', child: [] }))
    }
}

But this is not working, How can I fix this ?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can check if any of the elements in the data have a matching ID using Array.some and if not then you can use concat or just the spread operator to add the new object to the existing data.

function arrayHandler(question) {
  if (!data.some((d) => question.id === d.parentId)) {
    setData((data) => [...data, { parentId: question.id, userChoice: "NO", child: [] }]);
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I think that now it shold work

function arrayHandler(question) {
const hasParentId = data.find((object) => question.id === object.parentId)
// concat if array do not have any question with same id. 
if (!hasParentId) {
  setData((data) => data.concat({ parentId: question.id, userChoice: 'NO', child: [] }))
}

}

about 4 years ago · Juan Pablo Isaza 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