How to put the states taken from the ibge site in alphabetical order?

Asked

Viewed 276 times

-2

 fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados")
    .then( res => res.json() )
    .then( states => {

    for( const state of states ) {
        ufSelect.innerHTML += `<option value="${state.sigla}">${state.sigla}</option>`
    }

        
    })
}

populateUFs()

function getCities(event) {
    const citySelect = document.querySelector("[name=city]")
    const stateInput = document.querySelector("[name=state]")
    
    const ufValue = event.target.value

    const indexOfSelectedState = event.target.selectedIndex
    stateInput.value = event.target.options[indexOfSelectedState].text

    const url = `https://servicodados.ibge.gov.br/api/v1/localidades/estados/${ufValue}/municipios`


    citySelect.innerHTML = "<option value>Selecione a cidade</option>"
    citySelect.disabled = true

    fetch(url)
    .then( res => res.json() )
    .then( cities => {
        
    for( const city of cities ) {
        citySelect.innerHTML += `<option value="${city.nome}">${city.nome}</option>`
    }

    citySelect.disabled = false
        
    })

}


document
   .querySelector("select[name=uf]")
    .addEventListener("change", getCities)
  • 1

    You inserted a lot of code into the question without need, it would be enough to show the format that is receiving the Api states and what you tried to do to sort!

1 answer

2


To organize a particular array, the Javascript provides a call function sort.

According to the documentation, you can pass a function to have custom criteria. This function must return one of the possible values, which are: -1, 0 or 1.

Example:

arr.sort((a, b) => a > b ? 1 : -1)
  • If to is less than b, must return -1
  • If to is greater than b, must return 1
  • If to is equal to b, must return 0

const ufSelect = document.querySelector('#ufSelect');

fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados")
    .then( res => res.json() )
    .then( res => {
      return res.sort((a, b) => a.sigla > b.sigla ? 1 : -1)
    })
    .then( states => {
      for( const state of states ) {
          ufSelect.innerHTML += `<option value="${state.sigla}">${state.sigla}</option>`
      }
    })
<select id="ufSelect" name="state"></select>

  • Thank you very much my friend! Gave it right here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.