You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中按指定规则对嵌套Map进行排序?

解决JavaScript嵌套Map的排序问题

首先,你的原函数在处理同一城镇重复数据时存在逻辑冗余,先优化这部分逻辑,再实现排序需求:

步骤1:优化数据处理逻辑

原代码中else块循环内层Map的操作完全没必要,直接判断内层Map是否已存在该城镇即可,代码更简洁高效:

function travelTime(array) {
    let countryOrdersMap = new Map();

    for (let command of array) {
        let [country, townName, cost] = command.split(" > ");
        cost = Number(cost);

        // 若国家不存在,创建新的内层Map
        if (!countryOrdersMap.has(country)) {
            countryOrdersMap.set(country, new Map());
        }
        let townMap = countryOrdersMap.get(country);
        // 若城镇已存在,取最小费用;否则直接添加
        if (townMap.has(townName)) {
            townMap.set(townName, Math.min(townMap.get(townName), cost));
        } else {
            townMap.set(townName, cost);
        }
    }

    // 添加排序逻辑并返回结果
    return sortNestedMap(countryOrdersMap);
}

步骤2:实现嵌套排序逻辑

要实现要求的排序规则,需要分别处理外层和内层Map:

  • 外层Map:提取所有国家键,按字母升序排序,再生成新的有序Map
  • 内层Map:提取每个国家对应的城镇-费用键值对数组,按费用降序排序,再生成新的有序内层Map
function sortNestedMap(originalMap) {
    // 1. 外层按国家字母升序排序
    const sortedCountries = Array.from(originalMap.keys()).sort();
    const sortedOuterMap = new Map();

    for (const country of sortedCountries) {
        const townMap = originalMap.get(country);
        // 2. 内层按费用降序排序
        const sortedTowns = Array.from(townMap.entries()).sort((a, b) => b[1] - a[1]);
        sortedOuterMap.set(country, new Map(sortedTowns));
    }

    return sortedOuterMap;
}

测试与输出

调用函数并打印结果:

const result = travelTime([
    "Bulgaria > Sofia > 1000",
    "Bulgaria > Sopot > 800",
    "France > Paris > 2000",
    "Albania > Tirana > 1000",
    "Bulgaria > Sofia > 1200"
]);

// 打印排序后的结构
for (const [country, towns] of result) {
    console.log(`${country}:`);
    for (const [town, cost] of towns) {
        console.log(`  ${town} -> ${cost}`);
    }
}

输出结果:

Albania:
  Tirana -> 1000
Bulgaria:
  Sofia -> 1000
  Sopot -> 800
France:
  Paris -> 2000

关键说明

  • JavaScript的Map是插入有序的,排序后必须重新构建新Map才能保留排序后的顺序
  • 提取Map的键或键值对时,用Array.from()转为数组才能使用数组的sort()方法
  • 内层排序时,b[1] - a[1]实现费用降序,若要升序则改为a[1] - b[1]

内容的提问来源于stack exchange,提问作者iNfRaSoNiC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:35:16