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

JavaScript: Removing all Objects that are equal in just a single attribute from Array

I have an Array of Geography-Location-Objects of this kind:

   let markers = [
   {
    "markerOffset": 10,
    "name": "Plantation",
    "coordinates": ["9.85804","53.5233"]
   },
   {
    "markerOffset": 10,
    "name": "Roasting",
    "coordinates": ["29.85804","50.5233"]
   },
   {
    "markerOffset": 10,
    "name": "Packaging",
    "coordinates": ["29.85804","50.5233"]
   },
{
    "markerOffset": 10,
    "name": "Harbour",
    "coordinates": ["21.85804","51.5213"]
   },
]

How can I filter the array to remove duplicate objects with the same coordinates (such as element 2 and 3) and only leave one entry with the coordinates.

A Set wont work propably because of the differing name: attribute

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 :

Simple compare and build a new array. This doesn’t care about the name attribute and just uses the first one that comes along

let markers = [
   { "markerOffset": 10, "name": "Plantation", "coordinates": ["9.85804","53.5233"] },
   { "markerOffset": 10, "name": "Roasting", "coordinates": ["29.85804","50.5233"] },
   { "markerOffset": 10, "name": "Packaging", "coordinates": ["29.85804","50.5233"] },
   { "markerOffset": 10, "name": "Harbour",  "coordinates": ["21.85804","51.5213"] },
]

let results = [];
markers.forEach(marker => {
    if(!results.find(m => m.coordinates[0] === marker.coordinates[0] &&  m.coordinates[1] === marker.coordinates[1] )) results.push(marker);
})

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