0

I have a json url that I want to use for my google charts - specifically I'm making a table if "aggregated results," ie volume of a specific month.

I'm grabbing my json using $.getJson, but I'm having trouble figuring out how I can do calculations on the json other than looping through. Can I make a secondary function in another file to declutter if a for loop is all I can do?

Thanks

1 Answers1

0

once you have created the DataTable
there are Data Manipulation Methods you can use to group and aggregate the data

you can use the standard agg functions...

google.visualization.data.avg
google.visualization.data.count
google.visualization.data.max
google.visualization.data.min
google.visualization.data.sum

or write your own, the function will receive an array of values from the column provided

column definition:

{'column': 3, 'aggregation': doubleSum, 'type': 'number', 'label': 'double minutes'}

agg function:

function doubleSum(values) {
  var groupValue = 0;
  values.forEach(function (v) {
    groupValue += (v * 2);
  });
  return groupValue;
}

see following working snippet...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable({
      cols: [
        {id: 'dat_ym', label: 'Start Date', type: 'date'},
        {id: 'user-id', label: 'User-Id', type: 'string'},
        {id: 'customer-id', label: 'Customer-Id', type: 'string'},
        {id: 's_minutes', label: 'minutes', type: 'number'}
      ],
      rows: [
        {c:[{v: new Date('2016, 01, 01')}, {v: '44836'}, {v: '67205'}, {v: 1122} ]},
        {c:[{v: new Date('2016, 01, 01')}, {v: '86495'}, {v: '67205'}, {v: 332} ]},
        {c:[{v: new Date('2016, 01, 01')}, {v: '44836'}, {v: '228626'}, {v: 90} ]},
        {c:[{v: new Date('2016, 01, 01')}, {v: '86495'}, {v: '228626'}, {v: 334} ]},
        {c:[{v: new Date('2016, 02, 01')}, {v: '44836'}, {v: '67205'}, {v: 554} ]},
        {c:[{v: new Date('2016, 02, 01')}, {v: '86495'}, {v: '67205'}, {v: 819} ]},
        {c:[{v: new Date('2016, 02, 01')}, {v: '44836'}, {v: '228626'}, {v: 420} ]},
        {c:[{v: new Date('2016, 02, 01')}, {v: '86495'}, {v: '228626'}, {v: 544} ]},
      ]
    });

    // group data by date, customer
    var grouped_data = google.visualization.data.group(
      data,
      [0, 2],
      [
        {'column': 3, 'aggregation': google.visualization.data.sum, 'type': 'number'},
        {'column': 3, 'aggregation': doubleSum, 'type': 'number', 'label': 'double minutes'}
      ]
    );

    // use custom aggregation
    function doubleSum(values) {
      var groupValue = 0;
      values.forEach(function (v) {
        groupValue += (v * 2);
      });
      return groupValue;
    }

    var chart = new google.visualization.Table(document.getElementById('chart_div'));
    chart.draw(grouped_data);
  },
  packages:['table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
WhiteHat
  • 59,912
  • 7
  • 51
  • 133