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

How to get all unique objects (with two values) in an array?

I’m storing some coordinates in an array. It looks like this:

const coords = [{x: 260, y: 60}, {x: 180, y: 0}, {x: 180, y: 240}, {x: 360, y: 120}, {x: 180, y: 60}, {x: 180, y: 60}, {x: 180, y: 60}]

How can I filter this array so the objects are unique, meaning there are no duplicates of objects with same x and y value? Expected output should be:

const coords = [{x: 260, y: 60}, {x: 180, y: 0}, {x: 180, y: 240}, {x: 360, y: 120}, {x: 180, y: 60}]

I’ve seen some similar solutions, but they didn’t really solve this problem.
I started with the following function

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

const output = Object.values(
  coords.reduce( (c, e) => {
    if (!c[e.x]) c[e.x] = e;
    return c;
  }, {})

but it only returns objects with different x values, so it just completely ommits y value.

>Solution :

One idea is to use a Set, map the x & y into a string, and then deserialize the Set to have unique x,y’s..

eg..

const coords = [{x: 260, y: 60}, {x: 180, y: 0}, {x: 180, y: 240}, {x: 360, y: 120}, {x: 180, y: 60}, {x: 180, y: 60}, {x: 180, y: 60}];

const dedup = [...new Set(coords.map(m => `${m.x}:${m.y}`))].map(m => {
  const [x,y] = m.split(':').map(n => n | 0);
  return {x,y};
});

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