2 回答
TA贡献1780条经验 获得超1个赞
再试一次 :)
const obj = {"Learn JavaScript": 3, "Learn React": 2, "manicure": 1};
function MinMaxFromObj(obj) {
const min = Math.min(...Object.values(obj));
const max = Math.max(...Object.values(obj));
const minKey = Object.entries(obj).find(([key, value]) =>
value === min ? key : null);
const maxKey = Object.entries(obj).find(([key, value]) =>
value === max ? key : null);
return [Object.fromEntries([minKey]), Object.fromEntries([maxKey])];
}
console.log(MinMaxFromObj(obj));
TA贡献2041条经验 获得超4个赞
这是一种可以帮助您解决问题的方法:
const minMaxEntry = (object) => {
let minKey;
let minValue = Infinity;
let maxKey;
let maxValue = -Infinity;
for (const key in object) {
if (object[key] < minValue) {
minKey = key;
minValue = object[key];
}
if (object[key] > maxValue) {
maxKey = key;
maxValue = object[key];
}
}
const minEntry = { [minKey]: minValue };
const maxEntry = { [maxKey]: maxValue };
return [minEntry, maxEntry];
};
// --- //
const object = {
"Learn JavaScript": 3,
"Learn React": 2,
"manicure": 1,
};
const [minEntry, maxEntry] = minMaxEntry(object);
console.log('Min Entry =>', minEntry);
// { "manicure": 1 }
console.log('Max Entry =>', maxEntry);
// { "Learn JavaScript": 3 }
添加回答
举报