[Chartjs]-Nest function not summarising values

1👍

The problem here is quite simple: all your nested_data nest is inside the row function.

The row function is called for each row in your CSV. As the API says,

If a row conversion function is specified, the specified function is invoked for each row, being passed an object representing the current row (d), the index (i) starting at zero for the first non-header row, and the array of column names.

However, that simply won’t work for the nest. The nest() method needs to get all the data array.

That being said, just move the nest to inside the then. As you can see, your nest itself has no issues:

const csv = `Year,Month,Country,Amount
2019,2,Germany,70 2019,3,Germany,65
2019,1,Germany,61
2019,1,Germany,39
2019,1,Italy,11966
2019,5,Italy,2489
2019,1,Italy,2262
2019,6,Germany,139
2019,4,Germany,111
2019,5,Germany,69
2019,6,Germany,67`;

const data = d3.csvParse(csv, d3.autoType);

const nested_data = d3.nest()
  .key(function(d) {
    return d.Country
  })
  .rollup(function(s) {
    return d3.sum(s, function(d) {
      return d.Amount;
    })
  })
  .entries(data);

console.log(nested_data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Leave a comment