Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Cómo construir una matriz para comparar primero y luego agregar la entrada

Debido a que soy un principiante en reaccionar y js, estoy teniendo dificultades para construir una matriz correctamente, encontré un artículo en la web según el cual usar el método concat puede construir una matriz. He seguido la misma técnica, pero mi problema es que agrega los datos y no los compara si los mismos datos ya están allí. Quiero comparar los datos antes de agregarlos a la matriz para que no entren datos duplicados en la matriz.

Mi código actual es:

 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) }

Aquí userInput es un objeto con múltiples valores de cadenas como

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

y si la matriz tiene el elemento con id: 1, al presionarlo nuevamente, no debería agregarse a la matriz.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puede usar la find de matriz para verificar si la matriz tiene un objeto con la misma identificación y, si no, puede agregar el valor

 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 Report

0

Puede verificar si la matriz contiene un elemento con la identificación con 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!