1

如何按数据点列表分组并按天聚合它们?例如,给定这个列表:

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
4

2 回答 2

1

假设您将数据点作为一个名为的字符串数组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})
于 2012-05-04T15:01:55.743 回答
0

T我不得不做出将日期与时间分开的假设。您可以使用正则表达式或子字符串提取日期,然后添加到计数中。我使用了正则表达式。

http://jsfiddle.net/p3ADG/

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>");   
}
于 2012-05-04T14:59:44.497 回答