如何通过某个值获取 Map 键?例如。 Map.prototype.get -> 按最低值键

How Can I get the Map key by a certain value? E.g. Map.prototype.get -> key by the lowest value

假设我的 elementsMap 具有以下键值对:

{ 'A' => 11, 'B' => 8, 'C' => 6 } 

如何通过最小值获取key

有关地图,请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get

编辑:请不要将其转换成数组

附录

如果我最终使用 TypeScript 和下面的解决方案,我会遇到一些麻烦:

function getMinKeyOfMap (map: Map<string,number>): string | undefined {
    let minKey: string;
    map.forEach((v,k)  =>{
        if (minKey === undefined || map.get(minKey) > v) {
            // map.get(minKey): Object is possibly 'undefined'.ts(2532)
            minKey = k;
        }
    });
    return minKey; // Variable 'minKey' is used before being assigned.ts(2454)
   
}

我对这个答案并不完全满意,但我不想再让别人紧张了,..

只需展开地图并减少 key/value 对。要获取密钥,请取数组的第一项。

const
    map = new Map([['A', 11], ['B', 8], ['C', 6]]),
    smallest = [...map].reduce((a, b) => a[1] < b[1] ? a : b)[0];

console.log(smallest);

无需将地图转换为数组,您可以使用 for ... of statement

直接迭代地图

let map = new Map([['A', 11], ['B', 8], ['C', 6]]),
    smallest;

for (const [k, v] of map)
    if (smallest === undefined || map.get(smallest) > v)
        smallest = k;

console.log(smallest);

Map#forEach

let map = new Map([['A', 11], ['B', 8], ['C', 6]]),
    smallest;

map.forEach((v, k) => {
    if (smallest === undefined || map.get(smallest) > v)
        smallest = k;
});

console.log(smallest);