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

Remove all unique values and keep all duplicates in an array

I have an object array and I want to filter it so that it only contains duplicates (by duplicates I mean objects that have the same value for the key number) and remove objects that have a unique number value. I want to keep all duplicate objects (not just identify what the duplicate values are!). The duplicates will always be in consecutive order.

My array:

const array = [
  {
   number: 1,
   color: "red"
  },
  {
   number: 2,
   color: "blue"
  },
  {
   number: 2,
   color: "yellow"
  },
  {
   number: 3,
   color: "black"
  },
  {
   number: 3,
   color: "orange"
  },
  {
   number: 4,
   color : "white"
  }
]

Expected output :

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

[
  {
   number: 2,
   color: "blue"
  },
  {
   number: 2,
   color: "yellow"
  },
  {
   number: 3,
   color: "black"
  },
  {
   number: 3,
   color: "orange"
  }
]

I have searched high and low but all answers seem to either remove or identify duplicates and since I’m new to javascript I don’t have the skills to modify those codes to work for me. Any help is greatly appreciated!

>Solution :

A straightforward approach is to filter the array and retain all elements for which you can find some element with the same number at a different position in the array:

const result = array.filter(
  (v1, i1, a) => a.some((v2, i2) => v1.number === v2.number && i1 !== i2)
);

Complete snippet:

const array = [
  {
   number: 1,
   color: "red"
  },
  {
   number: 2,
   color: "blue"
  },
  {
   number: 2,
   color: "yellow"
  },
  {
   number: 3,
   color: "black"
  },
  {
   number: 3,
   color: "orange"
  },
  {
   number: 4,
   color : "white"
  }
];

const result = array.filter(
  (v1, i1, a) => a.some((v2, i2) => v1.number === v2.number && i1 !== i2)
);

console.log(result);
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