如何按数据点列表分组并按天聚合它们?例如,给定这个列表:
2012-03-18T00:00:04
2012-03-18T00:05:03
2012-03-19T00:10:04
2012-03-19T00:15:03
2012-03-19T00:20:03
2012-03-19T00:25:03
我希望有:
2012-03-18,2
2012-03-19,4
如何按数据点列表分组并按天聚合它们?例如,给定这个列表:
2012-03-18T00:00:04
2012-03-18T00:05:03
2012-03-19T00:10:04
2012-03-19T00:15:03
2012-03-19T00:20:03
2012-03-19T00:25:03
我希望有:
2012-03-18,2
2012-03-19,4
假设您将数据点作为一个名为的字符串数组points
var map = {};
points.forEach(function(x) {
var s = x.split("T")[0];
if(map.hasOwnProperty(s)) {
map[s]++;
}
else {
map[s] = 1;
}
});
这为您提供了该日期每次出现的计数。
例子
js> points
["2012-03-18T00:00:04", "2012-03-18T00:05:03", "2012-03-19T00:10:04", "2012-03-19T00:15:03", "2012-03-19T00:20:03", "2012-03-19T00:25:03"]
js> points.forEach(function(x) {
var s = x.split("T")[0];
if(map.hasOwnProperty(s)) {
map[s]++;
}
else {
map[s] = 1;
}
});
js> map
({'2012-03-18':2, '2012-03-19':4})
T
我不得不做出将日期与时间分开的假设。您可以使用正则表达式或子字符串提取日期,然后添加到计数中。我使用了正则表达式。
var count = {};
var input = [
"2012-03-18T00:00:04",
"2012-03-18T00:05:03",
"2012-03-19T00:10:04",
"2012-03-19T00:15:03",
"2012-03-19T00:20:03",
"2012-03-19T00:25:03"
];
for(var i = 0; i < input.length; i++) {
var date = /(.*)T/.exec(input[i])[1];
if(!count[date]) {
count[date] = 1;
}
else {
count[date] += 1;
}
}
for (var date in count) {
document.write(date+","+count[date]+"<br>");
}