Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Node JS code to load JSON document with countries and prepare some useful Sets with unique collections of data from the JSON document
var countriesDocumentURL = "https://raw.githubusercontent.com/mledoze/countries/master/countries.json"
request(countriesDocumentURL, async function (error, response, body) {
var countries = JSON.parse(body)
// get unique region values (see: https://codeburst.io/javascript-array-distinct-5edc93501dc4)
// take all elements in the countries array, for each of them: take the region element; create a Set of all the resulting region values (a Set contains unique elements)
var regions = [...new Set(countries.map(country => country.region))]
var subregions = [...new Set(countries.map(country => country.subregion))]
// see https://stackoverflow.com/questions/39837678/why-no-array-prototype-flatmap-in-javascript for this flatMap function
const flatMap = (f, xs) =>
xs.reduce((acc, x) =>
acc.concat(f(x)), [])
// take all elements in the countries array, for each of them: take the array of languages ); create one big array of all small arrays of languages (this is what the flatmap does) and turn that big array into a Set (of unique language values)
var languages = [...new Set(flatMap(country => Object.values(country.languages), countries))]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.