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

215
Vistas
How to construct an Array to first compare and then add the input

Due to being a beginner in react and js I'm having a hard time to construct an array properly, I found an article on web according to that using concat method can construct an array. I have followed the same technique, But my problem is it appends the data and dost compare if the same data already there. I want to compare the data before appending into array so no duplicate data gets into the array.

My current code is:

const [input, setInput] = useState([]) // state

const handleOnChange = (userInput) => {
    // Add the userInput the list onChange of userInput
    // Save userInput to React Hooks
    
    setInput((input) => input.concat(userInput))
    console.log(input)
  }

Here userInput is and object with multiple strings values like

{id: 1 , ifYes: "Do this", ifNo : "Do something else"}

and if array has the item with id:1 then hitting it again it shouldn't append to the array.

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

0

You can use array find to check if the array has an object with same id and if not then you can add the value

const [input, setInput] = useState([]) // state

const handleOnChange = (userInput) => {
  // Add the userInput the list onChange of userInput
  // Save userInput to React Hooks
  const hasUserInput = input.find(userVal => userVal.id === userInput.id);
  if (!hasUserInput) {
    setInput((input) => input.concat(userInput));
    console.log(input)
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You could check if the array contains an element with the id with some(...).

const [input, setInput] = useState([]) // state

const handleOnChange = (userInput) => {
    // Add the userInput the list onChange of userInput
    // Save userInput to React Hooks
    if(!input.some(i => i.id === userInput.id)){
        setInput((input) => input.concat(userInput))
    }
    console.log(input)
}
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