Recently, I stumbled upon an API that provides a list of countries and their corresponding cities. You can check out the API here.
Upon fetching the data, I noticed there were duplicate entries for some cities within the same country. Here's an example from the response:
{
"country": "United States",
"cities": [
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbotsford",
],
},
To clean up these duplicates, I wrote a function which does the job, but it feels a bit clunky. Here is my code snippet:
getCountries = async () => {
if(!this.mounted) return;
interface typeData {
data: Array<{country: string, cities: Array<string>}>;
error: boolean;
msg: string;
}
const result: typeData = await this.data.GetCountries();
let findDuplicates = result.data.map(i => {
let currentCountry = i.country;
let currentCities: Array<string> = [];
i.cities.filter(c => {
if(!currentCities.includes(c)) currentCities.push(c);
});
let finalArray: Array<{country: string, cities: Array<string>}> = [{
country: currentCountry,
cities: currentCities
}];
return finalArray;
}).reduce((sofar, current) => [...sofar, ...current], []);
findDuplicates && this.setState({data: {weather: this.state.data?.weather, countries: findDuplicates}})
}
I'm wondering if there is a more efficient way to achieve this task using a one-liner with methods like reduce, map or filter. The examples I found so far don't quite match the structure of my data:
Array<{country: string, cities: Array<string>}>.