0

I have the current code that attempts to build a 2d array for the google charts.

However I get an invalid 2D array error.

What am i doing wrong? Thank you in advance

//Request data
        $.getJSON(api,function(data){

            //Init final array for data
            var finalData = [["SessionLength"]];

            //Iterate over results
            for (var key in data){

                //Get the key pair
                 var keyPair = [key, parseInt(data[key])];

                //Add to array
                 finalData.push(keyPair);
             }

            // Create the data table.
            var data = google.visualization.arrayToDataTable(finalData);

            // Set chart options
            var options = {'title':'Average session length',
                'width':400,
                'height':400};

            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        });

This is the JSON

{"2013-8-5":"13.5","2013-7-29":"19.7","2013-8-4":"12.2","2013-8-3":"14.1","2013-8-2":"10.1","2013-7-31":"15.1","2013-7-30":"17.4","2013-8-6":"16.0","2013-8-1":"15.0"}
William Falcon
  • 9,813
  • 14
  • 67
  • 110

2 Answers2

3

I think your doing wrong the 2D array initialization You should just write

var finalData = [];

because var finalData = [["SessionLength"]]; is creating an array which have single element as ["SessionLength"] which is one element array, then you are adding arrays which have 2 elements, so actually you get an invalid 2D array like this:

[["SessionLength"], ["2013-8-5", "13.5"], ["2013-7-29","19.7"]...]
Armen
  • 287
  • 1
  • 8
3

Your finalData array's first element needs to be a 2-element array:

var finalData = [['Date', 'SessionLength']];
asgallant
  • 26,060
  • 6
  • 72
  • 87