Skip to content
Advertisement

Dynamic number of keys in the d3 v6 rollups

I am using d3 v6 rollups to create a nested data structure. I have an array ‘feature_vars’ that contains the variables I want to use for nested grouping. Right now, I can do this for two variables like below.

feature_vars = ['v0','v1']
data = d3.rollups(data, v => v.length, 
                d => d[feature_vars[0]], d=>d[feature_vars[1]]])

The problem is feature_vars is dynamic and can contain any number of variables. So, how do I make it generic so that is works for any number of variables in the feature_vars array?

Advertisement

Answer

One way would be to use the destructuring assignment:

  const feature_vars = ['v0','v1'],
        maps = feature_vars.map(fv => function(d) {return d[fv]}),
        data = d3.rollups(data, v => v.length, ...maps)
Advertisement