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

204
Views
Remove object value in array if it doesn't exist

I have an array of objects as follows

const array = [ 
{id:1,parentIds:[]}
{id:2,parentIds:[1,3]}
{id:3,parentIds:[1,2,4]}
]

How can I make it possible to remove an object's parentIds value if it doesn't exist in the array? to look something like this

const array = [ 
{id:1,parentIds:[]}
{id:2,parentIds:[1,3]}
{id:3,parentIds:[1,2]}
]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can try this solution:

const array = [{
    id: 1,
    parentIds: []
}, {
    id: 2,
    parentIds: [1, 3]
}, {
    id: 3,
    parentIds: [1, 2, 4]
}];

const idsArr = new Set(array.map(el => el.id));

array.forEach(el => {
    el.parentIds = el.parentIds.filter(el => idsArr.has(el));
})
    
console.log(array);

about 4 years ago · Juan Pablo Isaza Report

0

It's better to avoid mutating the original array parentIds, use immutation to create new array:

const array = [ 
{id:1,parentIds:[]},
{id:2,parentIds:[1,3]},
{id:3,parentIds:[1,2,4]}
]

const ids = array.map(({id}) => id)

const newArray = array.map(({parentIds,...arrayItemRest}) => {
  const newparentIds = parentIds.filter(id => ids.includes(id))
  
  return {
    ...arrayItemRest,
    parentIds: newparentIds
  }
})
about 4 years ago · Juan Pablo Isaza Report

0

const array = [ 
{id:1,parentIds:[]},
{id:2,parentIds:[1,3]},
{id:3,parentIds:[1,2,4]}
]

// Let's create an array only containing the ids
var ids = array.map(o => o.id)

// Loop array
array.forEach((object) => {
  // Loop all parent ids
  object.parentIds.forEach((id, index) => {
    // Check if we find the id in our list
    if (ids.indexOf(id) === -1) {
      // Delete item from array if not found
      object.parentIds.splice(index, 1)
    }
  })
})

// The result
console.log(array)

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!