Reputation: 17
I have the csv file
DATE OF ARREST, ARREST RESOLUTION, COUNT
01/01/1988, BONDED OUT, 1
01/01/1988, BONDED OUT, 1
01/01/1988, BONDED OUT, 1
02/01/1988, BONDED OUT, 1
02/01/1988, BONDED OUT, 1
I want to create a chart view with the data above. To do this, I have to sum "COUNT" for each date. For example, I need to have 01/01/1988, BONDED OUT, 3 ... in this day I have 3 cases. To parse the date I use
var parseDate = d3.timeParse("%m/%d/%Y");
data.forEach(
function(d){
d.count = +d["COUNT"];
d.date = parseDate(d["DATE OF ARREST"]);
})
The chart shows the year correctly, but the number of cases is always 1. How can I count the "COUNT" for each year?
Upvotes: 0
Views: 1041
Reputation: 8509
If I understand you correctly, you want to convert your data and sum all COUNT
for the same day. You can do it with d3.nest.
var dataAsCsv = `DATE OF ARREST,ARREST RESOLUTION,COUNT
01/01/1988,BONDED OUT,1
01/01/1988,BONDED OUT,1
01/01/1988,BONDED OUT,1
02/01/1988,BONDED OUT,1
02/01/1988,BONDED OUT,1`;
var data = d3.csvParse(dataAsCsv);
var parseDate = d3.timeParse("%m/%d/%Y");
var convertedData = d3.nest()
.key(function(d) { return d["DATE OF ARREST"]; })
.rollup(function(v) {
return {
date: parseDate(v[0]["DATE OF ARREST"]),
count: d3.sum(v, function(d) { return +d["COUNT"]; })
}
})
.entries(data).map(function(d) { return d.value});
console.log(convertedData);
<script src="https://d3js.org/d3.v4.min.js"></script>
Upvotes: 1