Home > Software engineering >  Deleting All the similar object from array if it has duplicates
Deleting All the similar object from array if it has duplicates

Time:11-15

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!

CodePudding user response:

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

CodePudding user response:

  • Find unique's values in an array.
const ressult = YourArray.filter(
  (value, index, array) => array.findIndex((v) => v.code === value.code) === index
);
  • Related