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 stop adding duplicate data to Array in react.js

I followed the approach as the answer in this question suggested The issue is that I want to construct an Array using setState and I dont; want to add duplicate data.

here is the sample data

const data = [
  {
    parentId: '1',
    userChoice: 'NO',
    child: []
  },
  {
    parentId: '2',
    userChoice: 'NO',
    child: []
  },
}

I'm catching the parentId from question.id from user input. If there is the same question then I don't want to concat into the array.

This is how I'm trying.

const [data, setData] = useState([]) // state

function arrayHandler(question) {
    const hasParentId = data.find((parentId) => question.id === parentId)
    // concat if array do not have any question with same id. 
    if (!hasParentId) {
      setData((data) => data.concat({ parentId: question.id, userChoice: 'NO', child: [] }))
    }
}

But this is not working, How can I fix this ?

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

0

You can check if any of the elements in the data have a matching ID using Array.some and if not then you can use concat or just the spread operator to add the new object to the existing data.

function arrayHandler(question) {
  if (!data.some((d) => question.id === d.parentId)) {
    setData((data) => [...data, { parentId: question.id, userChoice: "NO", child: [] }]);
  }
}
about 4 years ago · Juan Pablo Isaza Report

0

I think that now it shold work

function arrayHandler(question) {
const hasParentId = data.find((object) => question.id === object.parentId)
// concat if array do not have any question with same id. 
if (!hasParentId) {
  setData((data) => data.concat({ parentId: question.id, userChoice: 'NO', child: [] }))
}

}

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!