Q:

D3.JS and mapping buckets

I'm very new to D3 and I'm having trouble understanding how to access a 'sum' field from D3. With a basic aggregation I'm able to easily map fields with the following command:
var load_data = resp.aggregations.my_summary.buckets.map(function(d) {
        return {
            letter: d.key,
            frequency: d.doc_count
        }
    });

The problem occurs when a response is formatted like this:
    "buckets": [
               {
               "1": {
                  "value": 5975
               },
               "key": "XXXXXXXXXXXX",
               "doc_count": 5376
            },
Really what I need is the same "key" field from the original function but the frequency to be the value of that data above.
Thank you for any help!
-John

A:

If I understand your question correctly, you will have many anonymous objects with the same key, but different frequencies.  You want to sum each unique key to total the cumulative frequencies.
You can use the Array.reduce() method to help you solve this.  I'm not sure how D3 is needed here -- were you trying to use the d3.sum() method?
var b = [
  {key: 'a', freq: 45454}, {key: 'a', freq: 4545}, 
  {key: 'b', freq: 1232}, {key: 'b', freq: 4544}
];

var counts = b.reduce(function(p, d) {
  if (d.key in p)
    p[d.key] += d.freq;
  else
    p[d.key] = d.freq;

  return p;
}, {});

