0

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.

Image is below: enter image description here

3
  • Where do the column headings come from? Commented Aug 13, 2020 at 19:35
  • Just add a row to the table before the loop that adds the contents of tableData. Commented Aug 13, 2020 at 19:36
  • I added a row to the matrix at the top like this: transpose_array.unshift(dates_arr) Commented Aug 13, 2020 at 19:37

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

7 Comments

This just added another row on the top of all the dates
I thought that was what you wanted.
The first row doesn't get the green or red background colors.
Oh no, sorry. I want to add a column to the left of the first numbers
What should it contain, the array index?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.