w17w
w17w

Reputation: 65

Why does this code only display the last element in the array?

I have this code that I try to display on a web page

var record = [['Malaysia', 600], ['Germany', 500], ['Russia', 700], ['Canada', 900], ['United States', 300]];

for (var i = 0; i < record.length; i++) {

   var data = google.visualization.arrayToDataTable([
       ['Country', 'Density'],
       [record[i][0], record[i][1]],
       ]);
}

Supposedly, what I am trying to do is to have a variable 'record' that will store a multidimensional array as per the example above. Then, I would like to display all the elements inside the array side by side on a webpage. But, somehow it only displays the last element of the array which is ['United States', 300]. What are the suitable codes to fix this?

Upvotes: 1

Views: 71

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36574

I think you don't need a loop. Just pass the variable directly to the function using spread operator.

var data = google.visualization.arrayToDataTable(
       [
           ['Country', 'Density'],
           ...record,
       ]);

Upvotes: 1

Related Questions