rramona2
11/16/2017 - 5:13 PM

Google Apps Script's Charts Service uses a DataTable object as the source data for visualizations and tables. There is a built-in method tha

Google Apps Script's Charts Service uses a DataTable object as the source data for visualizations and tables. There is a built-in method that can create a DataTable given a Spreadsheet Range, but if you have a javascript table or array that you want to visualize, you need to use the DataTableBuilder class' primitive methods. This function simplifies that by making the same assumptions about your data that would be done with the native function building from a Range. This was written for StackOverflow question: http://stackoverflow.com/questions/21241086/category-filter-overlapping-content/21463756#21463756.

/**
 * Produce a dataTable object suitable for use with Charts, from
 * an array of rows (such as you'd get from Range.getValues()).
 * Assumes labels are in row 0, and the data types in row 1 are
 * representative for the table.
 *
 * @param {Array} data  Array of table rows
 *
 @ @returns {DataTable} Refer to GAS documentation
 */
function dataTableFromArray( data ) {
 var dataTable = Charts.newDataTable();
  for (var col=0; col<data[0].length; col++) {
    var label = data[0][col];
    var firstCell = data[1][col];
    if (typeof firstCell == 'string')
      dataTable.addColumn(Charts.ColumnType.STRING, label);
    else
      dataTable.addColumn(Charts.ColumnType.NUMBER, label);
  }
  for (var row = 1; row < data.length; row++) {
    dataTable.addRow(data[row]);
  }  
\!h   
  return dataTable.build();
}