title: Imitate a COUNT... GROUP BY in Cloudant (CouchDB)
body: <p>In CloudAnt, I want to get counts of features, grouped by two attributes: topics and councils. After a lot of fiddling, I was able to construct this:</p>
  
  <pre><code>// map
  function (doc) {
    if (doc.properties &amp;&amp; doc.properties.openCouncilDataTopic) {
      var ret = {};
      ret [doc.properties.openCouncilDataTopic] = {};
      ret [doc.properties.openCouncilDataTopic][doc.properties.sourceCouncilId] = 1;
  
      emit(null, ret);  
    } 
  }
  
  // reduce
  function (keys, values, rereduce) {
  
      var ret = values[0];
  
      function zero(x) { return x ? x : 0 }
      function add(i, topic, id) {
          ret[topic][id] = zero(ret[topic][id]) + values[i][topic][id];
      }
      function countTopic(topic) {
          if (!ret[topic])
              ret[topic] = {};
          Object.keys(values[i][topic]).forEach(add.bind(undefined, i, topic));
      }
      for (var i = 1; i &lt; values.length; i++) {
          Object.keys(values[i]).forEach(countTopic);
      }
      return ret;
  }
  </code></pre>
  
  <p>Is there a better way?</p>