Reputation: 634
I'm trying to fill a table with moment.js objects with each date's values on each column. The array I'm trying to fill the table with looks like this:
[['8th Jan 11AM', '8th Jan 12AM'],['9th Jan 11AM', '9th Jan 12AM'],['10th Jan 11AM', '10th Jan 12AM']]
I'm creating that array as so:
for (var i = 0; i < 7; i++) {
thisMoment = moment().day(i);
var dayDateStamps = [];
for (var j = 0; j < 12; j++) {
dayDateStamps.push(thisMoment.startOf('day').add(j + 6, 'hours').format('lll'));
}
dateStamps.push(dayDateStamps);
}
To generate the table I'm doing this:
function bodyFromDateStamps(dateStamps) {
var tbody = document.getElementsByTagName('tbody')[0];
for(var i = 0; i < countMultiArray(dateStamps); i++) {
if (i % 7 == 0) {
row = tbody.insertRow(tbody.rows.length);
}
row.insertCell(i % 7).innerHTML = dateStamps[i % 7][i];
}
}
function countMultiArray(array) {
var iter = 0
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
iter += 1
}
}
return iter;
}
However, currently I'm getting this:
I get the right amount of cells (84) however the content is stopping after 1 iteration of an 'hour' loop. I can't work out where I've gone wrong here.
How can I fix this issue and is there a better way to solve this problem? Any help is greatly appreciated!
Upvotes: 0
Views: 318
Reputation: 5413
The problem is generating the table.
You are iterating from 0 to 83, and trying to access an inner array by that i
. You are accessing the first array correctly using modulus, but the 2nd array index should also be bound to a 0-6 value index, so do this:
row.insertCell(i % 7).innerHTML = dateStamps[i % 7][Math.floor(i/12)];
Math.floor(i/12)
will correctly find the 2nd index in a 0 - 83 iteration.
BTW: countMultiArray
can be replaced with 7 * 12
, no need for that function because you already know the values.
Upvotes: 1