Skip to content
Advertisement

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:

{ '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

EDIT: Please do not convert it into an array

ADDENDUM

If I use finally TypeScript with the solution below, I get some troubles:

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,..

Advertisement

Answer

Just spread the map and reduce the key/value pairs. 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

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement