Search code examples
javascriptd3.jsnestedrollup

d3.nest rollup where keys are the categories of a column drilled down to a category in another column


I want to do a rollup by where the keys are the 'type' of the fruit 'banana'.

What I have:

var fruit_cnt = d3.nest()
        .key(function(d) {
            return d.fruit === "banana";
        })
        .rollup(function(o){
            return d3.sum(o, function(d){
                return d.count;
            });
        })
        .entries(dataset)
        .map(function(d){
            return {type: d.key, count: d.value};
        });

I end up getting true false values for the keys, but I want the keys to be 'Chiq' and 'Mont'.

Dataset:

[
    {
      "fruit": "banana",
      "type": "Chiq",
      "count": 1000
    },
    {
      "fruit": "banana",
      "type": "Mont",
      "count": 200
    },
    {
      "fruit": "watermelon",
      "type": "",
      "count": 100
    },
    {
      "fruit": "grape",
      "type": "",
      "count": 220
    }
  ]

Solution

  • You're mixing up the key method with filter:

    var fruit_cnt = d3.nest()
            .key(function(d) { return d.type })
            .rollup(function(o){
                return d3.sum(o, function(d){
                    return d.count;
                });
            })
            .entries(dataset.filter(function(d) { return d.fruit === "banana" }))
            .map(function(d){
                return {type: d.key, count: d.value};
            })