Reputation: 89
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"}
Upvotes: 2
Views: 86
Reputation: 22524
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; }
Upvotes: 2