'JavaScript Fetch and Sort in Alphabetic order (with Brazilian portuguese accented words) before populating a "select" [duplicate]
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.:
- São Paulo
- Santa Catarina
- Tocantins
and not:
- São Paulo
- Amapá
- Amazonas
Thanks.
Solution 1:[1]
You should use Array.sort
states.sort((a, b) => (a.nome > b.nome) ? 1 : (b.nome > a.nome) ? -1 : 0)
and pass Compare function to it
The purpose of the compare function is to define an alternative sort order. The compare function should return a negative, zero, or positive value
If the result is negative a is sorted before b.
If the result is positive b is sorted before a.
If the result is 0 no changes are done with the sort order of the two values
const ufSelect = document.querySelector("#ufSelect")
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 : (b.nome > a.nome) ? -1 : 0)
for (const state of states) {
ufSelect.innerHTML += `<option value="${state.id}">${state.nome}</option>`
}
})
<select id="ufSelect"></select>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
