我想找一个带下划线的最小值的键。例如:
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'我怎么能在得分不足的情况下做到这一点?
我试过:
_.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;
})但是它返回一个带有数字索引的数组,因此我的散列键丢失了。
发布于 2014-02-26 18:44:53
下划线或下划线< 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]
发布于 2014-02-26 18:46:18
你可以用reduce来做这件事
var result = _.reduce(my_hash, function(memo, val, key) {
if (val.value < memo.value || _.isNull(memo.value)) {
return {key: key, value: val.value};
} else {
return memo;
}
}, {key: "none", value: null});
console.log(result.key);产出:
0-23发布于 2014-02-26 18:48:55
_.reduce(my_hash, function(m, v, k, l) {
if (v.value <= l[m].value) {
m = k;
}
return m;
}, '0-0');https://stackoverflow.com/questions/22049946
复制相似问题