Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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 :

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)
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading