gpt4 book ai didi

javascript - 如何在带下划线的哈希中找到最小值的键

转载 作者:搜寻专家 更新时间:2023-11-01 04:52:02 25 4
gpt4 key购买 nike

我想找到带下划线的最小值的键。例如:

var my_hash = {'0-0' : {value: 23, info: 'some info'},
'0-23' : {value: 8, info: 'some other info'},
'0-54' : {value: 54, info: 'some other info'},
'0-44' : {value: 34, info: 'some other info'}
}
find_min_key(my_hash); => '0-23'

我如何使用 underscorejs 做到这一点?

我试过:

_.min(my_hash, function(r){
return r.value;
});
# I have an object with the row, but not it's key
# => Object {value: 8, info: "some other info"}

我也尝试对其进行排序(然后获取第一个元素):

_.sortBy(my_hash, function(r){ 
return r.value;
})

但它返回一个带有数字索引的数组,所以我的哈希键丢失了。

最佳答案

使用下划线或 Lodash < 4:

_.min(_.keys(my_hash), function(k) { return my_hash[k].value; });//=> 0-23

使用 Lodash >= 4:

_.minBy(_.keys(my_hash), function(k) { return my_hash[k].value; });//=> 0-23

没有图书馆:

Object.entries(my_hash).sort((a, b) => a[1].value - b[1].value)[0][0]

Object.keys(my_hash).sort((a, b) => my_hash[a].value - my_hash[b].value)[0]

关于javascript - 如何在带下划线的哈希中找到最小值的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22049946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com