I have multiple arrays lets say:
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple"];
I want to put this in 4-column table dynamically. if click on animals picture the animals array would fill the table, if food, then food array would fill the table.
So, lets say I have
<table class="myTable"></table>
Then need javascript
import $ from "https://cdn.skypack.dev/[email protected]";
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple"];
var $table = $('.myTable');
for (var i = 0; i < food.length; i++){
var $aSingleContent = '<tr><td>'+food[i]+'</td></tr>';
$table.append($aSingleContent);
}
This would display all food items in 1 column. Now I need to divide this by 4 – because 4 columns in a row
3
Answers
because of
<tr>
in linevar $aSingleContent = '<tr><td>'+food[i]+'</td></tr>';
makes your javascript create a new row for every element in array. we need to keep count the amount of data that had filled a row. if a row has 4 columnscolumnCount === 4
, then we create a new row.You can try this:
Hope this help!
If you have
food
array more than you provide you can use this one.