如何在带有下划线的哈希中找到min值的键

Ben*_*ier 4 javascript underscore.js

我想用下划线找到最小值的关键.例如:

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'
Run Code Online (Sandbox Code Playgroud)

我怎么能用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"}
Run Code Online (Sandbox Code Playgroud)

我也尝试对它进行排序(然后得到第一个元素):

_.sortBy(my_hash, function(r){ 
  return r.value; 
})
Run Code Online (Sandbox Code Playgroud)

但它返回一个带有数字索引的数组,因此我的哈希键丢失了.

Jam*_*urz 7

使用Underscore或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]