1

As an example, I have 3 arrays with same length:

arrayOne = ['a', 'b', 'c']

arrayTwo = ['d', 'e', 'f']

arrayThree = ['g', 'h', 'i']

I wish to know if there is a way to populate a HTML5 table by columns using jQuery (or even if this is the best practice for things like this). So far, I've seen this post.

This post came very close to answering my question but it doesn't use arrays.

The ideal solution would be to populate the table by having the number of rows same as the length of any of the arrays. (Users will be able to choose the length of the array(s), therefore, the number of rows... I think I got carried away).

For example:

Before

<table class="table">
    <thead class="thead-dark">
       <tr>
          <th scope="col">First Column</th>
          <th scope="col">Second Column</th>
          <th scope="col">Third Column</th>
       </tr>
     </thead>
     <tbody id="table-content">
     </tbody>
</table>

Expected Output

<table class="table">
    <thead class="thead-dark">
       <tr>
          <th scope="col">First Column</th>
          <th scope="col">Second Column</th>
          <th scope="col">Third Column</th>
       </tr>
     </thead>
     <tbody id="table-content">
       <tr>
         <td>a</td>
         <td>d</td>
         <td>g</td>
       </tr>
       <tr>
          <td>b</td>
          <td>e</td>
          <td>h</td>
       </tr>
       <tr>
          <td>c</td>
          <td>f</td>
          <td>i</td>
       </tr>
     </tbody>
</table>

The code I've tried was able to populate one of the columns, but I can't get any further.

const columnOne = arrayOne.map(p => {
     const rowItem = $('<td>').html(p)
     return $('<tr>').append(rowItem)
           })
$('#table-content').append(columnOne)
2
  • Generally it is easier to use d3 over jquery as a library to manipulate data and construct DOM elements using the data, including filling up tables. Commented Sep 3, 2019 at 3:43
  • Hello, I am a bit new to coding and wasn't able to find the meaning of the syntax in your code. Would you mind explaining what "$('<td>').html(p)" means? Thank you in advance! Commented Jul 23, 2020 at 8:40

4 Answers 4

2

Why exactly use two iterations??. Just a single straight iteration with the longest array length.

const arrayOne = ['a', 'b', 'c'];
const arrayTwo = ['d', 'e', 'f'];
const arrayThree = ['g', 'h'];

const maxSize = Math.max(arrayOne.length, arrayTwo.length, arrayThree.length);

for (let i = 0; i < maxSize; i++) {
  let row = $('<tr>');
  row.append($('<td>').html(arrayOne[i]));
  row.append($('<td>').html(arrayTwo[i]));
  row.append($('<td>').html(arrayThree[i]));
  $('#table-content').append(row);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <thead class="thead-dark">
    <tr>
      <th scope="col">First Column</th>
      <th scope="col">Second Column</th>
      <th scope="col">Third Column</th>
    </tr>
  </thead>
  <tbody id="table-content">
  </tbody>
</table>

Sign up to request clarification or add additional context in comments.

6 Comments

I ended up using this solution because of its efficiency. Thanks.
Hello, I am a bit new to coding and wasn't able to find the meaning of the syntax in your code. Would you mind explaining what "$('<td>').html(p)" means? Thank you in advance!
@webdesignnoob can you give me some context as to what p is? Basically, .html() is used to add html to the particular selector, which in your case is a <td>
@NidhinJoseph Oops, p seems to be arrayOne[i] in the code. I was specifically looking in the for loop with the line "row.append($('<td>').html(arrayOne[i]));" I am trying to convert this code in React, but I'm having a difficult time understanding what they are trying to do. If you could clarify, it would be much appreciated!
@Nidhin Joseph I actually figured out a different approach. Thank you for offering to helo though, I appreciate it!
|
2

Basically you need to create an array of row data, and then you can use your code to map that into table rows. I've taken a simplistic approach to make it easier to deal with an array which isn't the same length as the others.

const arrayOne = ['a', 'b', 'c'];
const arrayTwo = ['d', 'e', 'f'];
const arrayThree = ['g', 'h'];

// make a row array, adding blank values where insufficient data
const l = Math.max(arrayOne.length, arrayTwo.length, arrayThree.length);
let arrays = [];
for (let i = 0; i < l; i++) {
    arrays[i] = [
        arrayOne[i] || '',
        arrayTwo[i] || '',
        arrayThree[i] || ''
        ];
}        

const columns = arrays.map(p => {
    let row = $('<tr>');
    p.forEach(v => row.append($('<td>').html(v)));
    return row;
});
           
$('#table-content').append(columns)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
    <thead class="thead-dark">
       <tr>
          <th scope="col">First Column</th>
          <th scope="col">Second Column</th>
          <th scope="col">Third Column</th>
       </tr>
     </thead>
     <tbody id="table-content">
     </tbody>
</table>

1 Comment

Such a great answer! Not only did it solve my problem but i've got useful insight about the use of map() and forEach() together (great for a beginner in JS).
1

Here is a simple way using $.each().

arrayOne = ['a', 'b', 'c'];
arrayTwo = ['d', 'e', 'f'];
arrayThree = ['g', 'h', 'i'];

var newArray = [
  arrayOne, arrayTwo, arrayThree
];
$.each(newArray, function(index, tr) {
  var $tr = $('<tr>');
    $.each(tr, function(i, td) {
      $tr.append('<td>' + td + '</td>');
    })
    $('#table-content').append($tr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table">
    <thead class="thead-dark">
       <tr>
          <th scope="col">First Column</th>
          <th scope="col">Second Column</th>
          <th scope="col">Third Column</th>
       </tr>
     </thead>
     <tbody id="table-content">
     </tbody>
</table>

Comments

1

Non JQuery Solution

What you need is an array of rows. Simply put your column arrays in a parent array:

const rows = [arrayOne, arrayTwo, arrayThree];

Then you can use a double forEach loop to create the rows and columns:

const table = document.getElementById('my-table');
const tbody = table.querySelector('tbody');

const arrayOne = ['a', 'b', 'c'];
const arrayTwo = ['d', 'e', 'f'];
const arrayThree = ['g', 'h', 'i'];

const rows = [arrayOne, arrayTwo, arrayThree];

rows.forEach(row => {
  const tr = document.createElement('tr');
  
  row.forEach(d => {
    const td = document.createElement('td');

    td.textContent = d;
    tr.appendChild(td);
  });
  
  tbody.appendChild(tr);
});
<table id="my-table">
  <thead>
    <tr>
      <th>One</th>
      <th>Two</th>
      <th>Three</th>
  </thead>
  <tbody></tbody>
<table>

d3 solution

I recommend using d3 over jquery for data manipulation (see how to join data here):

const arrayOne = ['a', 'b', 'c'];
const arrayTwo = ['d', 'e', 'f'];
const arrayThree = ['g', 'h', 'i'];
const rows = [arrayOne, arrayTwo, arrayThree];

const tr = d3.select('#my-table tbody')
  .selectAll('tr')
  .data(rows)
  .join('tr')
  .selectAll('td')
  .data(row => row)
  .join('td')
  .text(d => d);
<script src="https://d3js.org/d3-selection.v1.min.js"></script>
<table id="my-table">
  <thead>
    <th>One</th>
    <th>Two</th>
    <th>Three</th>
  </thead>

  <tbody></tbody>
<table>

1 Comment

Alternatives to jQuery are always welcome. I'll check out d3.

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.