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

Deleting All the similar object from array if it has duplicates

I have an array of objects with duplicates:

[
  {
    "code": "d1",
    "title": "Title 1"
  },
  {
    "code": "d2",
    "title": "Title 2"
  },
  {
    "code": "d3",
    "title": "Title 3"
  },
  {
    "code": "d4",
    "title": "Title 4"
  },
  {
    "code": "d4",
    "title": "Title 4"
  },
  {
    "code": "d3",
    "title": "Title 3"
  }
]

So i want the output to be having only the once which doesn’t have duplicates included like below:

[
  {
    "code": "d1",
    "title": "Title 1"
  },
  {
    "code": "d2",
    "title": "Title 2"
  }
]

Any help would be appreciated, Thanks!

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 :

Here is one way of doing it:

const products=[
  {
"code": "d1",
"title": "Title 1"
  },
  {
"code": "d2",
"title": "Title 2"
  },
  {
"code": "d3",
"title": "Title 3"
  },
  {
"code": "d4",
"title": "Title 4"
  },
  {
"code": "d4",
"title": "Title 4"
  },
  {
"code": "d3",
"title": "Title 3"
  }
];

const res=Object.entries(products.reduce((a,c)=>{
   (a[c.code+"|"+c.title]??=[]).push(c);
   return a;
 },{})).reduce((a,[k,v])=>{
   if(v.length==1) a.push(v[0]);
   return a;
 },[]);

console.log(res);

My approach involves two .reduce() loops:

  • In the first one I generate an object that collects all elements of the original array behind a compound key made up of the properties of the elements.
  • the object is then converted into an array again with Object.entries()
  • and in a second .reduce() only those elements will be collected (i. e.: their first element) into the target array that have a length of 1
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