1

I have four arrays

arrayOne['orange','blue','green','red','yellow','purple','gray','tan','pink','violet']
arrayTwo['1001','1003','3453','78934','2389','3','8934']
arrayThree['TV','phone','laptop']
arrayFour['1','2','3','4','5','6','7','8','9','10']

I am making a table in html

<table class="table table-striped">
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
      <th>Column 4</th>
   </tr>
</thead>

I have a script that opens a modal and appends to the table I have tried to get it working for two columns but it is only populating the first column with ArrayOne contents

for (row = 0; row <$(this).data("arrayOne").length; row++ ){
  $("#myModal").find(".table").append("<tr>
  <td>"+$(this).data("arrayOne")[row]+"</td>"); 

  for (j = 0; j <$(this).data("arrayTwo").length; j++ ){
    $("#myModal").find(".table").append("<tr>
    <td>"+$(this).data("arrayTwo")[j]+"</td></tr></tbody></table>");
  } 
} 

With the code above it only prints out as

column1    column2    column 3    column 4
orange
blue
green
red
....
violet

The end result should look something like this

column1    column2    column 3    column 4
orange     1001       TV          1
blue       1003       phone       2
green      3453       laptop      3
red        78934                  4
yellow     2389                   5

Etc, Etc

1
  • you should try to close your <tr> before opening a new one.. EDIT: one of your problems is also that by appending raw html code, you should fill rows with all of your 4 arrays at once, because a <tr> is the horizontal part of that table Commented Aug 1, 2017 at 13:57

7 Answers 7

2

Assuming arrayOne has all the required rows, and on other arrays the rows may be blank, you can do something like,

 arrayOne.forEach(function(value, key){
     let firstColumn = arrayOne[key],
         secondColumn = arrayTwo[key]?arrayTwo[key]:"",
         thirdColumn = arrayThree[key]?arrayThree[key]:"",
         fourthColumn = arrayFour[key]?arrayFour[key]:"";

     $("#myModal").find(".table").append('<tr><td>'+firstColumn+'</td><td>'+secondColumn+'</td><td>'+thirdColumn+'</td><td>'+fourthColumn+'</td></tr>');
 });
Sign up to request clarification or add additional context in comments.

1 Comment

will end up with numerous "undefined" since arrays are different lengths
1

A jQuery solution to fill the table body can be:

var arrayOne = ['orange','blue','green','red','yellow','purple','gray','tan','pink','violet'];
var arrayTwo = ['1001','1003','3453','78934','2389','3','8934'];
var arrayThree = ['TV','phone','laptop'];
var arrayFour = ['1','2','3','4','5','6','7','8','9','10'];
for (var i = 0; i <arrayOne.length; i++ ){
    var row = $('<tr/>').append($('<td/>', {text: arrayOne[i] || ''}))
            .append($('<td/>', {text: arrayTwo[i] || ''}))
            .append($('<td/>', {text: arrayThree[i] || ''}))
            .append($('<td/>', {text: arrayFour[i] || ''}));
    $('table tbody').append(row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table class="table table-striped">
    <thead>
    <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
        <th>Column 4</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>

2 Comments

You have var row = $('<tr/>').append. So in my case do i need to find the modal table first. For example would it be $("#myModal").find(".table")$("<tr/>).append ?
@jumpman8947 Instead to use $('table tbody').append(row); you can write $("#myModal").find(".table")
1

Here you go with a solution https://jsfiddle.net/phru3m7s/1/

var arrayOne = ['orange','blue','green','red','yellow','purple','gray','tan','pink','violet'];
var arrayTwo = ['1001','1003','3453','78934','2389','3','8934'];
var arrayThree = ['TV','phone','laptop'];
var arrayFour = ['1','2','3','4','5','6','7','8','9','10'];


for(var i=0; i< arrayOne.length; i++){
	var tableString = "<tr>";
  	tableString += "<td>" + arrayOne[i] + "</td>";
    tableString += "<td>" + ((typeof arrayTwo[i] === 'undefined') ? '' : arrayTwo[i]) + "</td>";
    tableString += "<td>" + ((typeof arrayThree[i] === 'undefined') ? '' : arrayThree[i])  + "</td>";
    tableString += "<td>" + ((typeof arrayFour[i] === 'undefined') ? '' : arrayFour[i]) + "</td>";
  tableString += "<tr>";
  
  $('table tbody').append(tableString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
  <thead>
      <tr>
          <th>Column 1</th>
          <th>Column 2</th>
          <th>Column 3</th>
          <th>Column 4</th>
      </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Comments

1

var arrayOne = ['orange','blue','green','red','yellow','purple','gray','tan','pink','violet'];
var arrayTwo = ['1001','1003','3453','78934','2389','3','8934'];
var arrayThree = ['TV','phone','laptop'];
var arrayFour = ['1','2','3','4','5','6','7','8','9','10'];

//To test the longest array
var length_array = [];
length_array.push( arrayOne.length); 
length_array.push( arrayTwo.length); 
length_array.push( arrayThree.length); 
length_array.push( arrayFour.length); 

var maxLength = Math.max.apply( null, length_array );

for (var i = 0; i <maxLength; i++ ){
    var row = $('<tr/>').append($('<td/>', {text: arrayOne[i] || ''}))
            .append($('<td/>', {text: arrayTwo[i] || ''}))
            .append($('<td/>', {text: arrayThree[i] || ''}))
            .append($('<td/>', {text: arrayFour[i] || ''}));
    $('table tbody').append(row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table class="table table-striped">
    <thead>
    <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
        <th>Column 4</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>

Comments

1

You can try this

for (row = 0; row <$(this).data("arrayOne").length; row++ )
{
    var valOne = ($(this).data("arrayOne")[row]!=null)?$(this).data("arrayOne")[row]:"";
    var valTwo = ($(this).data("arrayTwo")[row]!=null)?$(this).data("arrayTwo")[row]:"";
    var valThree = ($(this).data("arrayThree")[row]!=null)?$(this).data("arrayThree")[row]:"";
    var valFour = ($(this).data("arrayFour")[row]!=null)?$(this).data("arrayFour")[row]:"";

    $("#myModal").find(".table").append("<tr><td>"+valOne+"</td><td>"+valTwo+"</td><td>"+valThree+"</td><td>"+valFour+"</td></tr>");
} 

1 Comment

arrays are different lengths
1

Approach to combine your individual arrays into one array and determine which is the longest then loop over that to generate the rows

var arrayOne = ['orange', 'blue', 'green', 'red', 'yellow', 'purple', 'gray', 'tan', 'pink', 'violet'],
  arrayTwo = ['1001', '1003', '3453', '78934', '2389', '3', '8934'],
  arrayThree = ['TV', 'phone', 'laptop'],
  arrayFour = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];

var columns = [arrayOne, arrayTwo, arrayThree, arrayFour];
// start from longest column array
var rows = columns.reduce((a, c) => {
    return c.length > a.length ? c : a;
  }, [])
  // map the longest to create all the rows
  .map((_, rowIdx) => {
    // map the cells for each row
    var cells = columns.map(colArr => $('<td>',{text: colArr[rowIdx] || '' }));
    // return new row and cells
    return $('<tr>').append(cells);    
  });
 
// append all the rows     
$('#myModal tbody').append(rows);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myModal">
  <table>
     <thead>
        <tr>
          <th>Column 1</th>
          <th>Column 2</th>
          <th>Column 3</th>
          <th>Column 4</th>
       </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

Comments

1

There is a modern and reasonably elegant way to do this using Array.prototype.reduce(), as you can see in the example below:

var arrayOne = ['orange', 'blue', 'green', 'red', 'yellow', 'purple', 'gray', 'tan', 'pink', 'violet'];
var arrayTwo = ['1001', '1003', '3453', '78934', '2389', '3', '8934'];
var arrayThree = ['TV', 'phone', 'laptop'];
var arrayFour = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var sumArray = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}];
var mergedArrays = [arrayOne, arrayTwo, arrayThree, arrayFour].reduce(function(sum, value, index) {
  for (var key in sum) {
    sum[key][index] = value[key];
  }
  return sum;
}, sumArray);

console.log(mergedArrays);

var htmlToRender = '<table class="table table-striped"><thead><tr><th>Column 1</th><th>Column 2</th><th>Column 3</th><th>Column 4</th></tr></thead><tbody>';

for (var key in mergedArrays) {
  htmlToRender += '<tr><td>' + mergedArrays[key][0] + '</td>';
  htmlToRender += '<td>' + mergedArrays[key][1] + '</td>';
  htmlToRender += '<td>' + mergedArrays[key][2] + '</td>';
  htmlToRender += '<td>' + mergedArrays[key][3] + '</td></tr>';
}

htmlToRender += '</tbody></table>';
$("#myModal").append(htmlToRender);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myModal">
</div>

Explanation

You essentially create an empty array of objects and then you accumulate the values of your existing arrays as objects with 4 values. After this is all done, you can iterate over the array of objects and write a new row in the table for each object in the array.

The code can be easily expanded and tweaked for more complex cases. Also, the length of the sumArray can be variable and tweaked based on your needs.

Also, as pointed out in this answer's comments, appending closing tags is a really bad practice, so the above code uses a better one, rendering the whole table instead of only its contents and the closing tags.

4 Comments

The concept of appending closing tags is all wrong. Not how the dom works
@charlietfl I totally agree with you, but the OP used this code, so I followed. I strongly disagree with using closing tags and, as a matter of fact, the optimal way in my opinion would be to render the whole table, as it makes little to no difference in the JS code and provides for a slightly easier manipulation and rendering. That's just me, though.
Doesn't matter that OP used it.... it does nothing and in fact can cause unexpected behavior. OP is misunderstanding how the dom works also
@charlietfl Agreed, it's a terrible idea. I actually updated my answer after researching it a little bit further. Thanks for pointing that out, appreciate it!

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.