简体   繁体   中英

Date manipulations in D3.js

How can I groupby a list of data points and aggregate them by day? for example, given this list:

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

I want to have:

2012-03-18,2
2012-03-19,4

Assuming you have the data points as an array of strings called points

var map = {};
points.forEach(function(x) {
  var s = x.split("T")[0];
  if(map.hasOwnProperty(s)) { 
    map[s]++;
  }
  else {
    map[s] = 1;
  }
});

This gives you a count of each occurrence of that date.

Example

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})

I had to make the assumption that T separates the date from the time. You can extract the date with a regular expression or a substring, and add to the tally. I used a regex.

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>");   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM