zubics zubics - 2 months ago 6
Javascript Question

Assign 2D-Array Values to HTML table using jQuery

I have a table from which I am getting values and storing it in a 2D-Array, then I take Transpose of this 2D Array and Store it another Array called Output Array, now I have to assign these values in td of previously used table.
Below is the code :



$(document).ready(function(){
var rows = [];
var output = [];
$("#btnTranspose").on("click",function(){
$("tr").each(function(){
var columns = [];
$(this).find("td").each(function(){
columns.push($(this).text());
});
rows.push(columns);
});
for(var i = 0; i < rows.length; i++){
output[i] = [];
for(var j = 0; j < rows[i].length; j++){
output[i][j] = rows[j][i];
}
}

$("tr").each(function(){
$(this).find("td").each(function(){
for(var k = 0; k < output.length; k++){
for(var l = 0; l < output[k].length; l++){
$(this).text(output[k][l]);
}
}
});
});
});
});

body{

}
table{
border: 1px solid black;
}
td{
border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Transpose Using jQuery</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table id="matrix">
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
<td>15</td>
</tr>
<tr>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
</tr>
</tbody>
</table>
<input type="button" value="Transpose!" id="btnTranspose">
<table id="outputTable">

</table>

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>





Problem is : code runs for every td and elements of Output array are assigned to each td, But I want to assign one element of Output Array to one td at a time. How do I do that?

Answer

each() callback provides you with the index for that instance. So when you iterate rows you already know the outer array index. Then when you iterate cells you have cell index

try

$("tr").each(function(rowIndex) {
  var rowData = output[rowIndex];
  $(this).find("td").each(function(cellIndex) {
    $(this).text(rowData[cellIndex]);
  });
});