So I found an API which I'm fetching all the countries and their respective cities. This is the API: https://documenter.getpostman.com/view/1134062/T1LJjU52#4829d16f-0f4e-43ec-886e-68ebad1221d8
I'm getting duplicates of cities back from the response, which I've checked in Postman, as can be seen below:
{
"country": "United States",
"cities": [
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbotsford",
],
},
I need to remove the duplicates, and I've managed to get it to work, but it's not too pretty... This is my function for formatting the code:
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}})
}
This feels like a not so efficient way to go about this, is there any way I can do this in a single line of code, with reduce, map or filter?
I've found similar examples on here, but none of them has this structure:
Array<{country: string, cities: Array<string>}>.