0

I'm having trouble adding rows to a google chart from an array. Right now I have the code below and it works fine. I want to use a for loop to add the rows instead of having to manually add in each one like I have it now when I was testing it out. How can I do that? The array has 30 elements in total.

function drawChart(array1) {

// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Day');
data.addColumn('number', 'Temperature');

data.addRows([

    [array1[29], array1[28]],
    [array1[27], array1[26]],
    [array1[25], array1[24]],
    [array1[23], array1[22]],
    [array1[21], array1[20]],

    ["Today", array1[0]]

]);


var options = {'title':'Historical Temperatures',

    hAxis: {
    title: 'Time',
    logScale: true
},
    vAxis: {
        title: 'Popularity',
        logScale: false
    },
    'width':700,
    'height':300};


var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Would replacing the data.addRows block with the following work?

for (var i = 20; i < array1.length; i+2)
{
    data.addRows([
        [array1[i+1], array1[i]]
    ])
}
2
  • Probably, have you tried it? Commented May 4, 2016 at 17:18
  • I tried it but the script / page crashes out and I need to force quit the browser. Commented May 4, 2016 at 17:27

1 Answer 1

1

There is a typo in your for loop:

for (var i = 20; i < array1.length; i+2) // it doesn't update i and enters an infinite loop

should be

for (var i = 20; i < array1.length; i+=2)
Sign up to request clarification or add additional context in comments.

1 Comment

Yep that was causing the issue. Thanks for finding that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.