I have been struggling with a problem. I have multidimensional array and i want to display it to table body. so i tried to do it with map, however i can't ignore the top of map element, so it displays like nest data.
this is how the multidimensioanl array looks
['2022-05-04', '2022-05-04', '2022-05-04', '2022-05-04', '2022-05-04', '2022-05-04']
['10:11:52', '10:11:52', '10:11:53', '10:11:54', '10:11:55', '10:11:56']
['447', '442', '447', '442', '436', '433']
so i tried to let it looks easy like below.
<tbody>
<tr>
<td>{list[0][0]}</td>
<td>{list[1][0]}</td>
<td>{list[2][0]}</td>
</tr>
<tr>
<td>{list[0][1]}</td>
<td>{list[1][1]}</td>
<td>{list[2][1]}</td>
</tr>
<tr>
<td>{list[0][2]}</td>
<td>{list[1][2]}</td>
<td>{list[2][2]}</td>
</tr>
<tr>
<td>{list[0][3]}</td>
<td>{list[1][3]}</td>
<td>{list[2][3]}</td>
</tr>
<tr>
<td>{list[0][4]}</td>
<td>{list[1][4]}</td>
<td>{list[2][4]}</td>
</tr>
</tbody>
so i tried to use map instead of doing this
const tableData = list.map((data, index) =>
data.map((item, idx) => (
<tr>
<td>{listData[idx]}</td>
</tr>
))
);
return(
<tbody>
{tableData}
</tbody>
)
it doesn't look what i expected. how can i solve this problem ?? "tr" tag length should be longest but "td" tag length should be the multidimensioanl array length.
CodePudding user response:
The data, as-is, isn't really suited to .map
because you need to iterate over the list[x][y]
s, where the x
changes, but not the y
. Turn the list into a structure where mapping will work first by essentially turning the multidimensional array on its side.
const tableData = list[0].map(
(_, i) => (
<tr>
{
list.map(
listItem => <td>{listItem[i]}</td>
)
}
</tr>
)
);
return (
<tbody>
{tableData}
</tbody>
)