Search code examples
javascripthtmlcss-tables

Table - How to skip displaying data in column1, while column2 has more than one line to display


How to skip displaying data in ItemA, while ItemB has more than one line to display:

ItemA = [Color Fruit, Nuts]

ItemB = [[green], [orange, apple, grapes], [cashew, almond]]

             if (this.point.customTT === 'Item') {
                    let tableBody = '';
                    itemA.forEach((name1, i) => {
                    itemB[i].forEach((name2, j) => {

                      tableBody += `
                          <tr>
                            <td >${itemA[i]}</td>
                            <td >${itemB[i][j]}</td>
                          </tr>
                     `

                   })
                   })

                   const html = `
                      <table>
                      <thead>
                      <tr>
                          <th>ItemA</th>
                          <th>ItemB</th>
                      </tr>
                      </thead>
                      <tbody>               
                      ${tableBody}
                      </tbody>
                  </table>
                 `
                 return html;
            }

Right now, above code returns table as below -> you can notice, fruit and nuts are written many a times

ItemA   ItemB

Color   Green
Fruit   Orange
Fruit   Apple
Fruit   Grapes
Nuts    
   

Like to display table as below - not repeat itemA

ItemA   ItemB

Color   Green
Fruit   Orange
        Apple
        Grapes
Nuts    

Solution

  • I've added an extra if statement to handle the case where itemA is longer than itemB :

    const ItemA = ["Color", "Fruit", "Nuts"];
    //const ItemB = [["green"], ["orange", "apple", "grapes"], ["cashew", "almond"]];
    const ItemB = [["green"], ["orange", "apple", "grapes"]];
    
    let tableBody = "";
    ItemA.forEach((name1, i) => {
      if (ItemB[i]) {
        ItemB[i].forEach((name2, j) => {
          tableBody += `
            <tr>
              <td >${j === 0 ? name1 : ""}</td>
              <td >${name2}</td>
            </tr>
       `;
        });
      } else {
        tableBody += `
      <tr>
        <td >${name1}</td>
        <td ></td>
      </tr>
    `;
      }
    });
    
    const html = `
        <table>
        <thead>
        <tr>
            <th>ItemA</th>
            <th>ItemB</th>
        </tr>
        </thead>
        <tbody>               
        ${tableBody}
        </tbody>
    </table>
    `;
    console.log(html);