0

I am building a small webapp and I am using this API which has around 485 objects in it. Those objects have specific property center. It can happen that the center property sometimes is equel (and not unique) to other object' center. How can I filter out the duplicates?

My code so far

function call() {

    fetch('https://data.nasa.gov/resource/9g7e-7hzz.json')
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            locations = data;
            getLocations(locations);
        })

}

function getLocations(locations) {

    //Filter out duplicates and push it to an array
    locations.forEach((location) => {

        console.log(location.center);

    })



}

enter image description here

So the result I expect is an array with objects, with unique values in the center property. Can someone help me out?

Giesburts
  • 6,879
  • 15
  • 48
  • 85

1 Answers1

0

Set can help you here:

function getLocations(locations) {
    let centers = new Set();
    let uniques = [];
    for (let location of locations) {
        if (!centers.has(location.center)) {
            centers.add(location.center);
            uniques.push(location);
        }
    }
    return uniques;
}
Máté Safranka
  • 4,081
  • 1
  • 10
  • 22