gpt4 book ai didi

javascript - 如何按值而不是键对 Map 对象数据进行排序?

转载 作者:行者123 更新时间:2023-12-04 09:00:24 25 4
gpt4 key购买 nike

我想看看是否有一种方法可以不按键 (app.id) 而是按值 (app.description) 对 Map 对象数据进行排序。例如,我有使用以下代码输入的以下数据:

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"}
我可以使用 javascript 的 sort 方法对这些数据进行排序,但它根据 id 对数据进行排序,如下所示:
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"}
我正在寻找的是这样的东西,其中数据按描述排序,如下所示:
所需输出:
[[Entries]]
0: {235 => "Initiative Project"}
1: {233 => "Management Cost"}
2: {231 => "Plan"}
3: {232 => "Project"}
4: {236 => "Project scoping"}
5: {234 => "Technical Assistance"}

最佳答案

您可以使用 entries()并对该数组进行排序并生成一个新的 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; }

关于javascript - 如何按值而不是键对 Map 对象数据进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63590687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com