I would like to use this API https://restcountries.com/#api-endpoints-v3-all
This is the link https://restcountries.com/v3.1/all
In this object, countries are not alphabetically sorted. How can I do it within the function?
const btn = document.querySelector("button");
const output = document.querySelector("#output");
const intake = document.querySelector("input");
const url = "https://restcountries.com/v3.1/all";
let myData = {};
fetch(url).then(function (res) {
return res.json()
}).then(function (data) {
myData = data;
buildSelect(data);
})
function buildSelect(d) {
let select = document.createElement('select');
d.forEach(function (item, index) {
let option = document.createElement('option');
console.log(item,index);
option.value = index;
option.textContent = item.name.common;
select.appendChild(option);
})
document.querySelector('body').appendChild(select);
}
The code belongs to Laurence Svekis, I'm doing his course, but in his version it's sorted by API side already.
Thank you!
CodePudding user response:
If the rest of the code works, then the only modification is a sort before the iteration that creates the options...
function buildSelect(data) {
sortedData = data.sort((a,b) => {
const aName = a.name.common;
const bName = b.name.common;
return (aName < bName) ? -1 : (aName > bName) ? 1 : 0;
});
let select = document.createElement('select');
sortedData.forEach(function (item, index) {
// ...
CodePudding user response:
You can sort the data before calling .forEach
within the buildSelect
function. I'd recommend sorting using localeCompare
as some of the common names in the data from https://restcountries.com/v3.1/all include non non-ASCII characters.
Quick example
d
.sort((a, b) => ('' a.name.common).localeCompare(b.name.common))
.forEach(function (item, index) {
let option = document.createElement('option');
console.log(item,index);
option.value = index;
option.textContent = item.name.common;
select.appendChild(option);
})
// If you must support IE you could replace the sort with...
// .sort(function(a, b) { return ('' a.name.common).localeCompare(b.name.common) }));
const btn = document.querySelector("button");
const output = document.querySelector("#output");
const intake = document.querySelector("input");
const url = "https://restcountries.com/v3.1/all";
let myData = {};
fetch(url).then(function (res) {
return res.json()
}).then(function (data) {
myData = data;
buildSelect(data);
});
function buildSelect(d) {
let select = document.createElement('select');
d
.sort((a, b) => ('' a.name.common).localeCompare(b.name.common))
//.sort(function(a, b) { return ('' a.name.common).localeCompare(b.name.common) })
.forEach(function (item, index) {
let option = document.createElement('option');
//console.log(item,index);
option.value = index;
option.textContent = item.name.common;
select.appendChild(option);
})
document.querySelector('body').appendChild(select);
}