问题描述
想象一下我的 elementsMap
有以下键值对:
{ 'A' => 11,'B' => 8,'C' => 6 }
怎样才能得到key的最小值?
对于地图,请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
编辑:请不要将其转换为数组
附录
如果我使用 finally 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)
}
我对这个答案并不完全满意,但我不想再让其他人紧张,..
解决方法
只需展开地图并减少键/值对。要获取密钥,请取数组的第一项。
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',smallest;
for (const [k,v] of map)
if (smallest === undefined || map.get(smallest) > v)
smallest = k;
console.log(smallest);
let map = new Map([['A',smallest;
map.forEach((v,k) => {
if (smallest === undefined || map.get(smallest) > v)
smallest = k;
});
console.log(smallest);