'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.
Solution 1:[1]
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)
}
}
Solution 2:[2]
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)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | brk |
| Solution 2 | jkoch |
