My question is about fetching and sorting data (which includes accented words) before populating a "select" field on my application.
This is my code for fetching and populating a list of states (that are being sorted by their id's, and not by their names):
function populateUFs() {
const ufSelect = document.querySelector("select[name=uf]")
fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados")
// .then( (res) => { return res.json() })
.then(res => res.json())
.then(states => {
for (const state of states) {
ufSelect.innerHTML += `<option value="${state.id}">${state.nome}</option>`
}
})
}
populateUFs()
<select name="uf">
</select>
How could I sort the list of states in alphabetic order, considering accented words please?
i.e.:
and not:
Thanks.
Use the Array.sort()
method.
states.sort((a, b) => a.nome < b.nome ? -1 : a.nome === b.nome ? 0 : 1)
function populateUFs() {
const ufSelect = document.querySelector("select[name=uf]")
fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados")
// .then( (res) => { return res.json() })
.then(res => res.json())
.then(states => {
states.sort((a, b) => a.nome < b.nome ? -1 : a.nome === b.nome ? 0 : 1)
for (const state of states) {
ufSelect.innerHTML += `<option value="${state.id}">${state.nome}</option>`
}
})
}
populateUFs()
<select name="uf">
</select>
Array.sort()
takes a sorting function that takes two elements of the array and returns a number which specifies which order they should be in.
if the number is positive sort the first element after the second element
if the number is negative sort the first element before the second element
if the number is zero don't change the order
(See this link for more information).
If you need your sort to work with accented characters use:
a.nome.localeCompare(b.nome)
instead of a.nome < b.nome ? ...