So I have a list of countries, by default they come sort by ISOA2 Code which is some kind of country code.
Say this list:
{
"AD": "Andorra",
"AE": "United Arab Emirates",
"AF": "Afghanistan",
"AG": "Antigua and Barbuda",
"AI": "Anguilla",
"AL": "Albania",
"AM": "Armenia",
"AN": "Netherlands Antilles",
"GB": "United Kingdom"
}
And I have this code:
function sortObject(obj) {
return Object
.keys(obj)
.sort()
.reduce((a, v) => {
a[v] = obj[v];
return a;
}, {});
}
// data is the list of countries
const result = sortObject(data);
I am trying to sort it with that code but it always returns the same list.
I need the list to be like this:
{
"AF": "Afghanistan",
"AL": "Albania",
"AD": "Andorra",
"AI": "Anguilla",
"AG": "Antigua and Barbuda",
"AM": "Armenia",
"AN": "Netherlands Antilles",
"AE": "United Arab Emirates",
"GB": "United Kingdom"
}
What am I doing wrong?
You can play around here:
https://codesandbox.io/s/js-playground-forked-xk005?file=/src/index.js
You will see the result in the console.
Take the Object.entries
sort them by value, then use Object.fromEntries
to turn this array of key-value pairs back into an object:
Object.fromEntries(
Object.entries(obj)
.sort(([keyA, valueA], [keyB, valueB]) => valueA.localeCompare(valueB))
)
Note that sorting objects is senseless if there are numeric keys or if the object is mutated (as that changes sort order again).
Try this for sorting:
const sortObject = obj => {
const ret = {}
Object.values(obj)
.sort()
.forEach(val => {
const key = Object.keys(obj).find(key => obj[key] === val)
ret[key] = val
})
return ret
}
Does this works for you?
function sortObject(obj) { return Object.fromEntries(Object.entries(obj).sort((a,b)=>a[1].localeCompare(b[1]))); } const data = { "AD": "Andorra", "AE": "United Arab Emirates", "AF": "Afghanistan", "AG": "Antigua and Barbuda", "AI": "Anguilla", "AL": "Albania", "AM": "Armenia", "AN": "Netherlands Antilles", "GB": "United Kingdom" } // data is the list of countries const result = sortObject(data); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.