Reputation: 53
I have a 2d array that populates a table. Is there a way to insert a column all the way to the left?
//function to create the table
function createTable(tableData) {
var table = document.createElement('table');
var row = {};
var cell = {};
tableData.forEach(function (rowData) {
row = table.insertRow(-1);
rowData.forEach(function (cellData) {
cell = row.insertCell();
cell.textContent = cellData;
let cellVal = cellData;
//make cells different shades of green and red for pos/neg (based on %)
if (cellVal > 0) {
cell.style.backgroundColor = '#00e100';
} else if (cellVal < 0) {
cell.style.backgroundColor = 'red';
}
});
});
document.body.appendChild(table);
}
createTable(transpose_array);
I dont want to add values to the table because of the color conditions, Id just like to add headers to each row on the y-axis of the table using values from an array I have.
Upvotes: 0
Views: 976
Reputation: 780843
The forEach()
callback gets a second argument containing the array index, you can use this to index into the headings array, and insert that as the first cell in each row.
//function to create the table
function createTable(tableData, row_headings) {
var table = document.createElement('table');
var row = {};
var cell = {};
tableData.forEach(function(rowData, i) {
row = table.insertRow(-1);
cell = row.insertCell();
cell.textContent = row_headings[i];
rowData.forEach(function(cellData) {
cell = row.insertCell();
cell.textContent = cellData;
let cellVal = cellData;
//make cells different shades of green and red for pos/neg (based on %)
if (cellVal > 0) {
cell.style.backgroundColor = '#00e100';
} else if (cellVal < 0) {
cell.style.backgroundColor = 'red';
}
});
});
document.body.appendChild(table);
}
createTable(transpose_array, price_array);
Upvotes: 1