Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
API - sort an external object

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!

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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) {
    // ... 
about 4 years ago · Santiago Trujillo Relatório

0

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);
}

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda