I have a nested object that looks like this.I want to sort this in ascending and descending order based on the alphabetical order of Districtnames.
var data =
{"DistrictC":{"population":105597},
"DistrictB":{"population":36842},
"DistrictA":{"population":238142}}
Expected output in ascending order is shown below.I also need to sort in descending order.
{"DistrictA":{"population":238142},
"DistrictB":{"population":36842},
"DistrictC":{"population":105597}}
You could use Object.entries to get an array of key/value pairs and then sort on the keys using localeCompare:
const data = {
"DistrictC":{"population":105597},
"DistrictB":{"population":36842},
"DistrictA":{"population":238142}
}
const sorted = Object.entries(data)
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB));
console.log(sorted);
You could make that result a bit easier to work with by collapsing the key/value arrays into objects using map:
// same as before
const data = {
"DistrictC":{"population":105597},
"DistrictB":{"population":36842},
"DistrictA":{"population":238142}
}
// same as before
const sorted = Object.entries(data)
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB));
const collapsed = sorted.map(([district, value]) => ({ district, ...value }));
// ascending
console.log(collapsed);
// descending
console.log(collapsed.reverse());