我有以下方法 -
// Push the date values into dateArray
var dateArray = [];
$.each(dateHtml, function (i, el) {
dateArray.push(htmlDateValue);
}
});
然后按最早日期排序 -
// sort array to have earliest date first
dateArray.sort(function (a, b) {
return new Date(b.date) - new Date(a.date);
});
给我留个例子 -
dateArray =
["02/10/2015 00:00:07",
"02/10/2015 00:00:08",
"02/10/2015 01:00:03",
"02/10/2015 01:00:05",
"02/10/2015 02:00:14",
"03/10/2015 07:00:37"];
我创建了 var arrOfCounts = [];
,我想用每个天中存在的每个小时的计数值来填充它。
例如,在上述数组中,结果应该是 -
arrOfCounts =
[2, // 2 instances of values within the hour of 00:00:00 on the 02/10/2015
2, // 2 instances of values within the hour of 01:00:00 on the 02/10/2015
1, // 1 instances of values within the hour of 02:00:00 on the 02/10/2015
1]; // 1 instances of values within the hour of 07:00:00 on the 03/10/2015
所以我开始循环 dateArray
中的每个值 -
$.each(dateArray, function (i, el) {
// Here I have to establish the value of count
arrOfCounts.push(count);
}
});
我怎样才能实现这个目标?
最佳答案
使用代表日期和时间的键创建自定义对象
var dates = ["02/10/2015 00:00:07",
"02/10/2015 00:00:08",
"02/10/2015 01:00:03",
"02/10/2015 01:00:05",
"02/10/2015 02:00:14",
"03/10/2015 07:00:37"
];
var counts = {};
dates.forEach(function(date) {
var dateS = date.split(' ')[0];
var hour = new Date(date).getHours();
if (typeof counts[dateS] == 'undefined') {
counts[dateS] = {};
}
if (typeof counts[dateS][hour] == 'undefined') {
counts[dateS][hour] = 0;
}
counts[dateS][hour] += 1;
});
console.log(counts);
关于javascript - 根据数组中的小时计算日期的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32908738/