tags:

views:

26

answers:

2

Here is what I have written:

var data = [["Jan","Feb","Mar"],["5","10","15"]];
var strTable = '<table>';
for (var i = 0; i < data.length; i++) {
    strTable += '<tr' + ((i % 2) ? ' class="odd"' : '') + '>';
    for (var j = 0; j < data[i].length; j++) {
        strTable += '<td>' + data[i][j] + '</td>';
    }
    strTable += '</tr>';
}
strTable += '</table>';

Which produces a table like so:

Jan | Feb | Mar
5   | 10  | 15

However I need to change this so that it produces:

Jan | 5
Feb | 10
Mar | 15

I am having a hard time trying to change the javascript around. Can anyone help?

+3  A: 

Here it is:

for (var i = 0; i < data[0].length; i++) { // instead of data.length
    strTable += '<tr' + ((i % 2) ? ' class="odd"' : '') + '>';
    for (var j = 0; j < data.length; j++) {  // instead of data[i].length
        strTable += '<td>' + data[j][i] + '</td>'; // instead of data[i][j]
    }
    strTable += '</tr>';
}

It gets the length of the first sub array in data, to know how many rows should be created. Then it iterates over the elements in data to create the columns.

This only works if all arrays have the same size or the first array contains the least elements. If you cannot assure this, an improvement would be to first calculate the number of elements of the array with the least elements.

Felix Kling
god I am such an idiot, thanks!
fire
+1  A: 

I'll community wiki this because it involves an additional resource, the Underscore.js library:

data = _.zip.apply(_, data);

That'll turn the "data" array sideways, and you could then proceed with the code that you already have.

Pointy