For a date/temperature scatter plot, I needed to organize the data with a date-like string. Here is the structure I came up with:
var dateTemperatures = {
'[2016,8,29]': {low: 63, high: 94},
'[2016,9,2]': {low: 59, high: 81},
'[2016,9,1]': {low: 58, high: 85}
}
The purpose was to parse the keys using JSON.parse and extract the necessary details for creating a date object. I stumbled upon this Stackoverflow answer which demonstrated how to construct an object using both apply
and new .... ()
. I applied this technique by substituting Something
with Date
:
var s = new (Function.prototype.bind.apply(Something, [null, a, b, c]));
This method worked effectively in a function I created to order the "Date" keys:
function orderTemperatureDates(dateTemperatures) {
var orderedDates = [];
for (var temperatureDate in dateTemperatures) {
var YMD = JSON.parse(temperatureDate);
YMD.unshift(null); //standard first argument to .apply()
orderedDates.push(new (Function.prototype.bind.apply(Date, YMD)));
}
return orderedDates.sort(function(a,b){return a.getTime() - b.getTime()});
}
Console output:
[Thu Sep 29 2016 00:00:00 GMT-0500 (Central Daylight Time), Sat Oct 01 2016 00:00:00 GMT-0500 (Central Daylight Time), Sun Oct 02 2016 00:00:00 GMT-0500 (Central Daylight Time)]
Regarding the example line from the mentioned Stackoverflow answer, there was confusion about how it works. According to the documentation, null
can be the first argument followed by the remaining arguments passed separately. However, in the example and my code, null and the arguments are placed within the same array.