Home > Blockchain >  How can I split table rows into 2 equal columns with JavaScript?
How can I split table rows into 2 equal columns with JavaScript?

Time:02-03

I have a script that will create some links inside table rows and display them.

$('#links').val('<>'   links.join('\n'));

$('#linksContainer').show();

What I would like to do before these are displayed is to split them into equal 2 columns and add them into the respective td. Something like this:

<table id="stylewithcss">
<tbody>

<tr>
<td  colspan="2">ADD HEADER HERE</td>
</tr>
<tr>

<td>
Here goes the first part of the links.
</td>

<td>
Here goes the second part of the links.
</td>

</tr>
</tbody>
</table>

I found something similar here but to be honest I don't really know how to apply it in my case (I am a beginner). convert single column to multiple columns

CodePudding user response:

You can try storing the links into an array, then divide the length of the array by 2 and display the first half in the first column and the second half in the second column. If the length is odd then push an empty string into the array to make it even. for example,

    var links=["link1","link2","link3","link4"];
    
    if(links.length % 2 == 1){
        links.push("");
    }
    
    var midpoint= links.length/2;
    var html='<tr><td  colspan="2">ADD HEADER HERE</td></tr>'
    
    for(i=0; i<midpoint; i  ){    
        html ='<tr><td>' links[i] '</td><td>' links[midpoint i]   '</td></tr>';   
    }
    document.getElementById('stylewithcss').innerHTML = html; 
<table id="stylewithcss">

</table>

CodePudding user response:

The simplest solution is to split it into 2 arrays (something like this):

for alternating:

const links = ["link one", "link two", "link three", "link four", "link five", "link six", "link seven", "link eight", "link nine"]

const linksOne = []
const linksTwo = []

for (let i = 0; i < links.length; i  ) {
  const link = links[i]
  if (i % 2 === 0) linksOne.push(link)
  else linksTwo.push(link)
}

for not alternating:

const links = ["link one", "link two", "link three", "link four", "link five", "link six", "link seven", "link eight", "link nine"]
const mid = Math.ceil(links.length / 2)

const linksOne = links.slice(0, mid)
const linksTwo = links.slice(mid)
  •  Tags:  
  • Related