0

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}}
1
  • 3
    Objects are not really meant to have order. JS Engines will keep order, but it is not guaranteed. Commented Nov 22, 2021 at 18:17

1 Answer 1

1

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());

Sign up to request clarification or add additional context in comments.

7 Comments

How to sort in descending order as well?
It is not sorting based on population....
It shouldn't. Read the question ( ascending and descending order based on the alphabetical order of Districtnames ) :P
In the reverse alphabetical order of district names , not based on population.
To reverse the order you could either swap keyA and keyB in the localeCompare expression: keyB.localeCompare(keyA), or just append .reverse() after the sort.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.