clintgh
clintgh

Reputation: 2077

Hide or remove column in Google Chart if rows are empty

In google chart (table is the chart type) how do I determine if rows in a column is empty and then hide that column?
for example:

[Boys] [Girls] [ 1 ] [ ] [ 3 ] [ ] [ 3 ] [ ]

Girls column is empty therefore hide or remove it, resulting in the table chart showing only the Boys column.

[Boys] [ 1 ] [ 3 ] [ 3 ]

Here is a sample of my code:

var datatable = new google.visualization.DataTable();

var rows = [
  {
    "Year": 2014,
    "Period": 3,
    "Segment": "*",
    "AnswerOption": 0,
    "AnswerValue": 5,
    "ResultCount": 2,
    "ResultAverage": 33.3333
  },
  {
    "Year": 2014,
    "Period": 4,
    "Segment": "*",
    "AnswerOption": 0,
    "AnswerValue": 5,
    "ResultCount": 5,
    "ResultAverage": 100.00
  }
]

datatable.addColumn('string', 'Year');
datatable.addColumn('number', 'Period');
datatable.addColumn('string', 'Segment');
datatable.addColumn('string', 'AnswerOption');
datatable.addColumn('number', 'AnswerValue');
datatable.addColumn('number', 'ResultCount');
datatable.addColumn('number', 'ResultAverage');


for(var j=0; j < rows.length; j++) {
datatable.addRows([
    [
        String(rows[j].Year),
        rows[j].Period,
        rows[j].Segment,
        rows[j].AnswerOption,
        rows[j].AnswerValue,
        rows[j].ResultCount,
        rows[j].ResultAverage,
    ]
 ]);    
}

In this example, all AnswerOption is 0 therefore google chart displays an empty cell.

Upvotes: 0

Views: 3380

Answers (1)

asgallant
asgallant

Reputation: 26340

You can parse your DataTable and construct a DataView that contains only columns that are not empty:

// assumes you have a DataTable "data"
var columns = [];
for (var i = 0; i < data.getNumberOfColumns(); i++) {
    for (var j = 0; j < data.getNumberOfRows(); j++) {
        if (data.getValue(j, i) !== null) {
            // add the column to the array if we find a value in it
            columns.push(i);
            // break because we don't need to search this column any more
            break;
        }
    }
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);

then use view to draw your Table, instead of using the DataTable.

Upvotes: 2

Related Questions