DEV Community

TEREN VELAN
TEREN VELAN

Posted on

Multi Dimensional Array in Tables

Recently at work i was tasked to add styling to a table , but what was special was that because i needed to make the borders of my table rounded , i had to target the four corners of the table.

That's where multi dimensional arrays come in , Tables are always multi dimensional , from row first followed by columns. So this requires a nested for loop and conditional statement to accurately pint point the exact element in the loop i want to style. And with arrays come indexes which makes it so much easier.

We start by looping through the top level array to display the table's TR:


pages.map((row , rowIndex) => {
  return (
    <Tr>

    </Tr>
 )
}

Enter fullscreen mode Exit fullscreen mode

Now that we have looped and displayed out

its time to loop through our content and display it within our , in a .

pages.map((row , rowIndex) => {
  return (
    <Tr>
      {row.cell.map((cell , cellIndex) => {
         return (
            <Td></Td>
           )
     })
    </Tr>
 )
}

Enter fullscreen mode Exit fullscreen mode

Now keep in mind that besides looping , we also need to pinpoint the

that are at the four corner of the table , so how do we do that , simply with array indexes.

In pseudo code:

Top left corner of table: row[0][0]
This finds the first row , and the first column element for that row

Top right corner of table row[0][cell.length -1]
This finds the first row and the last column element of that row

*For example purposes i will only show the 2 corners of the table

so placing this in a conditional as part of our loop:


pages.map((row , rowIndex) => {
  return (
    <Tr>
      {row.cell.map((cell , cellIndex) => {

       if(rowIndex === 0 && cellIndex === 0){
              return (
            <Td backgroudColor="red"></Td>
         )
     }else if (
       rowIndex === 0 && 
       cellIndex === row.cell.length -1 ){

        return (
            <Td backgroudColor="yellow"></Td>
         )
    } else {
         return (
            <Td backgroudColor="white"></Td>
         )
   }
     })
    </Tr>
 )
}

Enter fullscreen mode Exit fullscreen mode

By setting a conditional to check if the index matches the index of the row and column element that we want , in this case the corners of the table, we will be able to manipulate the data and even styling in the table freely.

This is my first step into learning how to manipulate tables and as a front-end developer this is very important, please do share with me if you do it differently.

And today's also my birthday so just want to give a shout out to my mentor Ian for his patience and guidance in teaching me. Thanks Ian!

Top comments (0)