To get the maximum and minimum values ββof the object key, if this is really what you have in mind, and not the key of the max and min values ββ(maybe itβs worth clarifying in your question), then for the example that you indicated, you can do it alternatively in pojs like that.
Javascript
function getMaxKey(object) { var max, i; for (i in object) { if (object.hasOwnProperty(i)) { if (!max) { max = i; } else if (i > max) { max = i; } } } return max; } function getMinKey(object) { var min, i; for (i in object) { if (object.hasOwnProperty(i)) { if (!min) { min = i; } else if (i < min) { min = i; } } } return min; } var test = { "2013-06-26": 839, "2013-06-25": 50, "2013-06-22": 25, "2013-05-14": 546, "2013-03-11": 20 }; console.log(getMaxKey(test)); console.log(getMinKey(test));
Output
2013-06-26 2013-03-11
Jsfiddle on
Or using ECMA5 Object.keys as suggested by @dandavis
Javascript
function getMaxKey(object) { return Object.keys(object).sort()[0]; } function getMinKey(object) { return Object.keys(object).sort().slice(-1)[0] } var test = { "2013-06-26": 839, "2013-06-25": 50, "2013-06-22": 25, "2013-05-14": 546, "2013-03-11": 20 }; console.log(getMaxKey(test)); console.log(getMinKey(test));
Jsfiddle on
If, on the other hand, you want to get the key from the maximum values ββof min, then you can do it in POJS.
Javascript
function getMaxKey(object) { var max, key, i; for (i in object) { if (object.hasOwnProperty(i)) { if (typeof max !== "number") { max = object[i]; key = i; } else if (i > max) { max = object[i]; key = i; } } } return key; } function getMinKey(object) { var min, key, i; for (i in object) { if (object.hasOwnProperty(i)) { if (typeof min !== "number") { min = object[i]; key = i; } else if (object[i] < min) { min = object[i]; key = i; } } } return key; } var test = { "2013-06-26": 839, "2013-06-25": 50, "2013-06-22": 25, "2013-05-14": 546, "2013-03-11": 20 }; console.log(getMaxKey(test)); console.log(getMinKey(test));
Jsfiddle on
In this case (with your specific test data) the output will be the same as in the previous example.
Or using ECMA5 Object.keys and Array.prototype.reduce
Javascript
function getMaxKey(object) { return Object.keys(object).reduce(function (previous, key) { return object[key] > object[previous] ? key : previous; }); } function getMinKey(object) { return Object.keys(object).reduce(function (previous, key) { return object[key] < object[previous] ? key : previous; }); } var test = { "2013-06-26": 839, "2013-06-25": 50, "2013-06-22": 25, "2013-05-14": 546, "2013-03-11": 20 }; console.log(getMaxKey(test)); console.log(getMinKey(test));
Jsfiddle on
This second example is easily executed using Underscore with some or all of these _.keys , _.min and _.max methods and the _.max has already been given.