When using the asynchronous function getProvinces()
on func initProvinces()
via axios.get
, the provinceCities
are not retrieved alphabetically, differing from their order in func initProvinces()
.
How could I change getProvinces()
to return the provinceCities
alphabetically?
Using Axios To Get The Data With getProvinces():
export async function getProvinces() {
const result = await axios.get(
`${process.env.NEXT_PUBLIC_API_ENDPOINT}/info/provinces`
);
return result.data;
}
Golang Function initProvinces() With The Data:
func initProvinces() {
provinceCities = make(map[string][]string)
//Anhui
provinceCities["安徽省"] = []string{"安庆市", "蚌埠市", "亳州市", "巢湖市", "池州市", "滁州市", "阜阳市", "广德市", "合肥市", "淮北市", "淮南市", "黄山市", "界首市", "六安市", "马鞍山市", "明光市", "宁国市", "潜山市", "宿州市", "天长市", "桐城市", "铜陵市", "芜湖市", "无为市", "宣城市"}
//Beijing
provinceCities["北京市"] = []string{"北京市"}
...
}
The list of provinces is much larger, and I've just included the first two.
The console.log of the data:
(33) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {province: '黑龙江省', cities: Array(33), autoPopulate: false}
1: {province: '天津市', cities: Array(1), autoPopulate: true}
Comparison, index 0 is '黑龙江省', whereas it should be "安徽省".
CodePudding user response:
From what I can tell you have a couple options for sorting the data:
- Return the data already sorted from the API
- Sort it locally in your UI code once it's received
I'm not familiar with GoLang to speak to the sorting on the API side (though I assume sorting is still a trivial call), but here's an example of sorting the response data on the app side in javascript.
Use a custom comparator to compare the province
property using String.prototype.localeCompare
. Note that you may need to also specify the locales
and options
arguments to customize the behavior to fit the language you're using.
const compareByProvince = (a, b) => a.province.localeCompare(b.province);
export async function getProvinces() {
const result = await axios.get(
`${process.env.NEXT_PUBLIC_API_ENDPOINT}/info/provinces`
);
return result.data.sort(compareByProvince);
}
CodePudding user response:
Front-end Solution:
When assigning the data to a prop to be passed down to the provinces.jsx
file, we were already using .map()
to get the relevant information into the component's return.
I thus used .sort()
to sort the information before mapping it. It didn't work when mapping it, then sorting it.
The end line of code looked like this:
const PROVINCE_OPTIONS = provinces.sort((x,y)=>x.province.localeCompare(y.province, 'zh-CN')).map((item) => item.province)