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