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

Delete objects from the array of object which reference id did not matches with any other object id from the same array of objects in javascript

I want to delete those objectσ which refId id that dont match with any id of array of object, if refId is null dont delete it

[
  {id: 1 , refId:null, name:'jhon'},
  {id: 2 , refId:null, name:'sam'}, 
  {id: 3 , refId:1, name:'fam'},
  {id: 4 , refId:2, name:'jam'}, 
  {id: 5 , refId:16, name:'ram'}, 
  {id: 6 , refId:15, name:'nam'}
]

result: should b:

[
  {id: 1 , refId:null, name:'jhon'}, 
  {id: 2 , refId:null, name:'sam'}, 
  {id: 3 , refId:1, name:'fam'},
  {id: 4 , refId:2, name:'jam'},
]

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

>Solution :

Please try once with following code:

const arr1 = [
  { id: 1, refId: null, name: "jhon" },
  { id: 2, refId: null, name: "sam" },
  { id: 3, refId: 1, name: "fam" },
  { id: 4, refId: 2, name: "jam" },
  { id: 5, refId: 16, name: "ram" },
  { id: 6, refId: 15, name: "nam" },
];

console.log(
  arr1.filter((obj) => {
    return obj.refId === null || arr1.some((o) => o.id === obj.refId);
  })
);
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