FindCountries
unknown
javascript
2 years ago
1.8 kB
14
Indexable
const findCountries = async (keyword, region) => {
const data = [];
// Get data for first page
// First page URL
const url = `https://jsonmock.hackerrank.com/api/countries/search?region=${region}&name=${keyword}&page=1`;
// Make GET request & get data for first page
const response = await fetch(url);
// Convert promise to JSON
const JSONData = await response.json();
// Extract data property from response JSON
data.push(...JSONData.data);
// Get data for 2nd page onwards if available
for (let page = JSONData.page + 1; page <= JSONData.total_pages; page++) {
// First page URL
const url = `https://jsonmock.hackerrank.com/api/countries/search?region=${region}&name=${keyword}&page=${page}`;
// Make GET request & get data for 2nd page and onwards
const response = await fetch(url);
// Convert promise to JSON
const JSONData = await response.json();
// Extract data property from response JSON
data.push(...JSONData.data);
}
// Now data variable declared on first line contains all extracte data
// that we need for further processing
// We will first sort data by population in increasing order and
// if two population are same then will further sort by it's name
data.sort((a, b) => {
return a.population !== b.population ?
a.population - b.population :
a.name.localeCompare(b.name);
});
// Map through sorted data and form string with
// Country name and it's poupaltion with a comma in between
// Following will return => eg - ['countryName,population', 'countryName_2,population_2', ...]
const result = data.map((item) => `${item.name},${item.population}`);
return result;
};Editor is loading...