I have a somewhat similar problem, and my solution may help others.
I have a list of "records", each record has a timestamp and value. I want to divide them into buckets, one for each day. In Python, I would use collection.defaultdict, but since JavaScript does not have something like this, I do the following.
If you want to read keys, remember that when using a date as a key object, it is converted as a string.
var get_entries = function() {
var entries = [];
entries.push({
'timestamp': 1381831606,
'value': 3
});
entries.push({
'timestamp': 1381831406,
'value': 2
});
entries.push({
'timestamp': 1381531606,
'value': 6
});
entries.push({
'timestamp': 1381221606,
'value': 9
});
entries.push({
'timestamp': 1381221601,
'value': 8
});
entries.push({
'timestamp': 1381221656,
'value': 7
});
return entries;
};
var normalize_date = function(timestamp) {
var dt = new Date(timestamp * 1000);
return new Date(
dt.getFullYear(),
dt.getMonth(),
dt.getDate()
);
};
var prepare_data = function() {
var entry,
line = {};
var entries_raw = get_entries();
for (var i = 0; i < entries_raw.length; i++) {
entry = entries_raw[i];
entry.date = normalize_date(entries_raw[i].timestamp);
console.log('Found entry for date', entry.date, 'with value', entry.value);
if (typeof(line[entry.date]) === 'undefined'){
line[entry.date] = 0;
}
line[entry.date] += entry.value;
}
console.log(line);
return line;
};
prepare_data();
Conclusion:
$ nodejs diaryindex.js
Found entry for date Tue Oct 15 2013 00:00:00 GMT+0200 (CEST) with value 3
Found entry for date Tue Oct 15 2013 00:00:00 GMT+0200 (CEST) with value 2
Found entry for date Sat Oct 12 2013 00:00:00 GMT+0200 (CEST) with value 6
Found entry for date Tue Oct 08 2013 00:00:00 GMT+0200 (CEST) with value 9
Found entry for date Tue Oct 08 2013 00:00:00 GMT+0200 (CEST) with value 8
Found entry for date Tue Oct 08 2013 00:00:00 GMT+0200 (CEST) with value 7
{ 'Tue Oct 15 2013 00:00:00 GMT+0200 (CEST)': 5,
'Sat Oct 12 2013 00:00:00 GMT+0200 (CEST)': 6,
'Tue Oct 08 2013 00:00:00 GMT+0200 (CEST)': 24 }
source
share