Home > Back-end >  How to construct an Array to first compare and then add the input
How to construct an Array to first compare and then add the input

Time:03-20

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.

CodePudding user response:

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

CodePudding user response:

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