Duplicate data from API
I’m fetching countries from the REST Countries API and displaying their regions in a dropdown.
Problem: every country comes with its region, so I keep getting repeated values like "Africa" 50+ times.
How do I display unique regions only?


24 Replies
add this before the forEach and change the foreach to run on regions instead of countries:
actually, just change the request
you don't need to fetch the region
actually, just the region
then use the set
if you just use this:https://restcountries.com/v3.1/all?fields=region
you will get an array with all the regions
that still requires the .map call and the set, it's just slightly less data transferred

Thank you so much @Jochem
Thank you so much guys
but it's a lot less data
assuming this is a simplification and the countries call is cached (either by Nephos or the browser) for later use, this could be more efficient too
as the regions (continents) probably wont change in the nearby future. I would just hardcode it. why take the time to fetch
translations is a good reason
the api offers translations
for the filter, you can just keep english (or region id). doens have to be translated. I dont know the api that well. but it seems a bit overkill
at least, that's what i understood from it
I actually need all the data,not just the region
Didn't even think of this
you're throwing all the data away to get the region
It's nice discovering something new in JavaScript, so i just had to try Set out
I'm just concerned about having two forEach,well maybe it's because i haven't formatted the code yet


I really don't understand, could you check this for my context


that's very very very different from the code you sent before
eh, you need one element for each country and one for each region, not really any way to avoid foreaches
you're already doing the one optimization I would do, which is to create the region array during the loop over the countries
but you can do it much better
you can just add directly to the set, instead of the array
that's fair, yeah
a lot of people will tell new folks to fear for loops and the like, but the reality is that you need to use them wisely. You can absolutely nest them, run a dozen of them in one bit of code, do all the things people tell you not to do as a beginner. You just need to be aware of how many items each loop is going to have, and make sure you don't end up with a thousand loops that run over ten thousand items each. If you've got reasonable sizes (300ish countries, 5 regions...) there's zero reason not to run simple code 300 times
but like... be aware that anything in that loop is going to run 300 times, so don't do heavy stuff in there
Noted
the only thing you should fear are errors and micro-optimizations
Yeah, I'm busting my head trying to figure out how a detailed of a clicked card would be displayed
depends on what you're trying to do
Something like this -- just more details about the country

looks good to me