Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get max and min keys from a collection with Underscore

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
}
like image 653
Sergei Basharov Avatar asked Feb 17 '23 02:02

Sergei Basharov


1 Answers

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);
like image 187
forivall Avatar answered Feb 18 '23 18:02

forivall