I have a DataTable that needs to be dynamically sorted using calculated values at run time. I have seen the sort method that exists on DataTable, but this appears to only allow passing a column which will then do a basic sort.

I would like to pass in a custom sort compare function; similar to how one can do with Array.prototype.sort

1 Answers

0
Vadim Gremyachev On

You could return a JSON representation of google.visualization.DataTable object and then apply arr.sort function to sort using a comparison function.

Below is provided a generic function for sorting DataTable:

function sortDataTable(dataTable,sortColumns)
{
    var json = dataTable.toJSON();
    var rows = JSON.parse(json).rows;
    rows.sort(function(a,b) {
        return sortColumns.func(a.c[sortColumns.column].v,b.c[sortColumns.column].v);
    });
    return new google.visualization.DataTable({cols: JSON.parse(json).cols, rows: rows});
}

Example

google.load("visualization", "1.1", { packages: ["table"] });
google.setOnLoadCallback(drawTable);

function drawTable() {
    
    getWeatherData(function (data) {
        var table = new google.visualization.Table(document.getElementById('table_div'));
        table.draw(data, { showRowNumber: true, width: '100%', height: '100%' });
    });
}



function getWeatherData(complete) {
    $.getJSON('https://gist.githubusercontent.com/vgrem/2d1436388ae8872f149d/raw/7193623c50cf2e093989391182aa67aaf8fdad2b/WeatherData.json', function (json) {
        var dataTable = new google.visualization.DataTable(json);
        //dataTable.sort({column: 1, desc: true});
        dataTable = sortDataTable(dataTable,{column: 1, func: sortTemperature}); //sort by second column (Temperature)
        complete(dataTable);
    });
}


function sortTemperature(a,b){
     if (a < b)
        return -1;
     if (a > b)
        return 1;
     return 0;
}


function sortDataTable(dataTable,sortColumns)
{
    var json = dataTable.toJSON();
    var rows = JSON.parse(json).rows;
    rows.sort(function(a,b) {
        return sortColumns.func(a.c[sortColumns.column].v,b.c[sortColumns.column].v);
    });
    return new google.visualization.DataTable({cols: JSON.parse(json).cols, rows: rows});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="table_div"></div>