Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  58] [ 4]  / answers: 1 / hits: 32682  / 11 Years ago, sun, april 7, 2013, 12:00:00

I'm trying to use Google's chart api: https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart



I have two arrays that I'd like to use to generate and label the visualization. However, I can't find a way to combine and convert these arrays into the proper object structure.



My arrays are the following and their contents are next to them:



years;   // 2014,2015,2020,2021
sales; // 100,100,200,100


I need to dynamically use these arrays to form this object, which is in the format that Google's API uses:



 var data = google.visualization.arrayToDataTable([
['Year', 'Sales'],
['2014', 100],
['2015', 100],
['2020', 200],
['2021', 100]
]);


Thank you for any help.


More From » arrays

 Answers
41

You should use addColumn and addRow in a for loop to go through your arrays.



Here is a sample:



function drawVisualization() {
// Create and populate the data table.
var years = ['2001', '2002', '2003', '2004', '2005'];
var sales = [1, 2, 3, 4, 5];

var data = new google.visualization.DataTable();
data.addColumn('string', 'years');
data.addColumn('number', 'sales');

for(i = 0; i < years.length; i++)
data.addRow([years[i], sales[i]]);

// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {});
}

[#79066] Friday, April 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristopher

Total Points: 58
Total Questions: 103
Total Answers: 102

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
;