简体   繁体   English

如何通过某个值获取 Map 密钥? 例如 Map.prototype.get -> key by the minimum value

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

Imagine my elementsMap has following key Value pairs:想象一下我的elementsMap有以下键值对:

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

How can I get the key by the lowest value?如何通过最低值获取密钥

For Maps, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get对于地图,请参阅: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get

EDIT: Please do not convert it into an array编辑:请不要将其转换为数组

ADDENDUM附录

If I use finally TypeScript with the solution below, I get some troubles:如果我最终使用 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)
   
}

I am not entirely satisfied with the answer but I don't want to strain other people's nerves any further,..我对答案并不完全满意,但我不想进一步拉伤其他人的神经,..

Just spread the map and reduce the key/value pairs.只需传播 map 并减少键/值对。 For getting the key take the first item of the array.要获取密钥,请获取数组的第一项。

 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);

Without converting map to an array, you could iterate the map directly, either with for... of statement or with在不将 map 转换为数组的情况下,您可以使用for... of语句或使用直接迭代 map

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM