Search code examples
dc.jscrossfilter

How to wrap a group with a top method


I have a map display and would like to total all electoral votes of the states that have been selected and display it in a number display. I was given the advice in a previous thread to wrap my group with an object with a top method. I'm not sure how to do this, so far I have:

var stateDim4 = ndx.dimension(function(d) { return d.state; }),
        group = stateDim4.group().reduceSum(function(d) {return d.elecVote }),
        count = group.top(51);
    count[0].key;
    count[0].value;

Please could someone help me on how to do this? Previous Thread: Summing a column and displaying percentage in a number chart


Solution

  • Building on your previous example, here is a fake group with a top method that sums up all the electoral votes for the selected states.

    var fakeGroup = {
        top: function() {
        return [
            grp2.top(Infinity).reduce(function(a,b) {
            if(b.value > 0) {
              a.value += elecVotesMap.get(b.key)
            }
            return a
          }, {
            key: "",
            value: 0
          })
        ]
      }
    }
    
    
    percentElec
      .group(fakeGroup)
      .formatNumber(d3.format("d")) 
    

    Here is a working JSFiddle: https://jsfiddle.net/esjewett/u9dq33v2/2/

    There are a bunch of other fake group examples in the dc.js FAQ, but I don't think any of them do exactly what you want here.