Dynamic filtering with D3
<p>I'm quite new to D3 and coding in general. I'm trying to set up a bar chart which includes/excludes data depending on a checkbox. I have a set of product groups and countries which I want to toggle in/out of the total represented by the bar. The output should be one bar per product.</p>

<p>My full data set has many more products, product groups and countries so it is not viable to create a key-value pair for each potential combination of checkboxes. Instead I would like to create a function that re-evaluates the checkboxes and re-filters the data and updates the rollup when a checkbox is changed.</p>

<p>I'm not sure where this function should sit in my code or what it should look like... This is what I'm working with at the moment:</p>

<pre><code>  var data = data.filter(function(d) {
    if (document.getElementById("nz_button").checked) {
      return d.country == 'NZ'
    }
    if (document.getElementById("au_button").checked) {
      return d.country == 'AU'
    }
    if (document.getElementById("us_button").checked) {
      return d.country == 'US'
    }
  })


  // to see how many distinct groups there are and sum volume
  var products = d3.nest()
    .key(function(d) {
      return d.product
    })
    .rollup(function(leaves) {
      var sum = 0;
      leaves.forEach(function(d) {
        sum += d.volume;
      })
      return sum
    })
    .entries(data);
</code></pre>

<p>Full code: <a href="http://plnkr.co/edit/qezdwMLt48RPc8KH17hS?p=preview" rel="nofollow">http://plnkr.co/edit/qezdwMLt48RPc8KH17hS?p=preview</a></p>

<p>Maybe I should be working with selections and re-running the nest/rollup when required?</p>

<p>Any help appreciated. Thanks :)</p>