How can I get max and min keys from this kind of a collection with Underscore? Seems to be an easy task but I didn't find a quick solution.
{
"2013-06-26":839,
"2013-06-25":50,
"2013-06-22":25,
"2013-05-14":546,
"2013-03-11":20
}
Unfortunately, _.min and _.max only support numbers, so we can't use those for your string keys. Fortunately, your dates are in a string-sortable format.
var minkey, maxkey;
_.each(obj, function(value, key) {
if (minkey == null || key < minkey) { minkey = key; }
});
_.each(obj, function(value, key) {
if (maxkey == null || key > maxkey) { maxkey = key; }
});
Now, if you really wanted the key of the max/min value, then it's this. Luckily, your values are numbers, so that makes it a little easier:
var keys = _.keys(obj);
function itemgetter(key) { return obj[key]; }
minkey = _.min(keys, itemgetter);
maxkey = _.max(keys, itemgetter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With