Home > other >  How to print 'State' values in react js in pattern given below using map?
How to print 'State' values in react js in pattern given below using map?

Time:10-23

 <tbody>
  {nums.map(index => {
           return (
                <tr >
                     <td>A</td>
                           {reservedSeat.map((obj, index) => {
                                   return (
                                                <>
                                                    <td><Button >{obj.seatno}</Button></td>
                                                </>
                                            )
                           })}
                    </tr>
                     )
        })}
 </tbody>

output i got : A001 A002 A003 A004 A005 B001 B002 B003 B004 B005 C001 C002 C003 C004 C005 \n A001 A002 A003 A004 A005 B001 B002 B003 B004 B005 C001 C002 C003 C004 C005 \n A001 A002 A003 A004 A005 B001 B002 B003 B004 B005 C001 C002 C003 C004 C005

pattern:

A001 A002 A003 A004 A005 \n
B001 B002 B003 B004 B005 \n
C001 C002 C003 C004 C005 \n

CodePudding user response:

Here is one approach. We can first join the entire array together on a single space. Then do a global regex search on the following pattern:

\w (?: \w ){4}

This will return an array of all row matches, which we can then join into a single string on newline.

state = ["A001","A002","A003","A004","A005","B001","B002","B003","B004","B005","C001","C002","C003","C004","C005"];
var output = state.join(" ").match(/\w (?: \w ){4}/g).join(" \n");
console.log(output);

CodePudding user response:

We can do it via slice() to let every 5 element in oneline and then output it in react

class App extends React.Component {
  render() {
    const state=["A001","A002","A003","A004","A005","B001","B002","B003","B004","B005","C001","C002","C003","C004","C005"]
    
    let data = []
    for(let i=0;i<state.length;i=i 5){
     data.push(state.slice(i,i 5).join(" ")) 
    }

    return (
      <ul>
       {
         data.map(d => {
           return <li>{d}</li>
         })
       }
      </ul>
    );
  }
}

ReactDOM.render(<App />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

  • Related