admin管理员组文章数量:1287596
I would like to find the key of a minimum value with underscore. For example:
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'
How can I do that with underscorejs ?
I've tried:
_.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"}
I also try to sort it (and then getting the first element):
_.sortBy(my_hash, function(r){
return r.value;
})
But it returns an array with numerical indexes, so my hash keys are lost.
I would like to find the key of a minimum value with underscore. For example:
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'
How can I do that with underscorejs ?
I've tried:
_.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"}
I also try to sort it (and then getting the first element):
_.sortBy(my_hash, function(r){
return r.value;
})
But it returns an array with numerical indexes, so my hash keys are lost.
Share Improve this question edited Feb 26, 2014 at 18:29 Benjamin Crouzier asked Feb 26, 2014 at 18:23 Benjamin CrouzierBenjamin Crouzier 42k48 gold badges177 silver badges239 bronze badges3 Answers
Reset to default 8With Underscore or Lodash < 4:
_.min(_.keys(my_hash), function(k) { return my_hash[k].value; }); //=> 0-23
With Lodash >= 4:
_.minBy(_.keys(my_hash), function(k) { return my_hash[k].value; }); //=> 0-23
Without a library:
Object.entries(my_hash).sort((a, b) => a[1].value - b[1].value)[0][0]
or
Object.keys(my_hash).sort((a, b) => my_hash[a].value - my_hash[b].value)[0]
You can do this with 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);
Outputs:
0-23
_.reduce(my_hash, function(m, v, k, l) {
if (v.value <= l[m].value) {
m = k;
}
return m;
}, '0-0');
本文标签: javascriptHow to find the key of the min value in a hash with underscoreStack Overflow
版权声明:本文标题:javascript - How to find the key of the min value in a hash with underscore - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741312943a2371753.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论