2

I am trying to see if there is a way to sort the Map object data not by the key (app.id) but by the value (app.description). For example, I have the following data that is coming in using the following code:

let newMap = new Map();
_.forEach(this.props.applicationTypes.APPLICATION_TYPE, (appType) => {
  newMap.set(appType.id, appType.description);
});
this.setState({applicationTpeMap: newMap});

[[Entries]]
  0: {234 => "Technical Assistance"}
  1: {235 => "Initiative Project"}
  2: {236 => "Project scoping"}
  3: {231 => "Plan"}
  4: {232 => "Project"}
  5: {233 => "Management Cost"}

I am able to sort this data using the sort method of javascript, but it sorts the data based of the id as seen below:

let newMap = new Map();
_.forEach(this.props.applicationTypes.APPLICATION_TYPE, (appType) => {
  newMap.set(appType.id, appType.description);
});
const mapAsc = new Map([...newMap.entries()].sort());
this.setState({applicationTpeMap: mapAsc});

[[Entries]]
  0: {231 => "Plan"}
  1: {232 => "Project"}
  2: {233 => "Management Cost"}
  3: {234 => "Technical Assistance"}
  4: {235 => "Initiative Project"}
  5: {236 => "Project scoping"}

what I am looking for is something like this where the data is sorted by the description such as the following:

Desired output:

[[Entries]]
0: {235 => "Initiative Project"}
1: {233 => "Management Cost"}
2: {231 => "Plan"}
3: {232 => "Project"}
4: {236 => "Project scoping"}
5: {234 => "Technical Assistance"}

1 Answer 1

2

You can use entries() and sort that array and generate a new map.

let newMap = new Map();
newMap.set(234, "Technical Assistance");
newMap.set(235, "Initiative Project");
newMap.set(236, "Project scoping");
newMap.set(231, "Plan");
newMap.set(232, "Project");
newMap.set(233, "Management Cost");
const sorted = new Map([...newMap.entries()].sort((a, b) => a[1].localeCompare(b[1])));
console.log([...sorted.entries()]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

Thank you so much @Hassan! This worked like a charm.

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.