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

214
Views
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.

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

0

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)
  }
}
about 4 years ago · Juan Pablo Isaza Report

0

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