Print the values in group of two in reactjs using .map()

Viewed 369

I am trying to render a <li> which will print two to values in a single line. And then the third to value in the next <li>. So my object is like this.

let obj = [ 
{from : 'a1' , to : 'a7'},
{from : 'b1' , to : 'b7',
{from : 'c4' , to : 'c27'},
{from : 'a1' , to : 'a9'},
{from : 'j1' , to : 'a10'}
]

I want to output it like

1. a7 , b7
2. c27, a9
3.  a10

The obj is a react state. I am printing it using .map() function in js. But I want it to print in pairs of two. How can I achieve that.

moves.map((move, i) => {
                            return (
                                <li key={i}>{i}
                                    {move}
                                </li>
                            )
                        })

2 Answers

First, you have to iterate your obj variable pariwise.

const moves = [];

  for (let i = 0; i < obj.length; i += 2) {
    let move = obj[i].to;
    if (i + 1 < obj.length) {
      move += ", " + obj[i + 1].to;
    }
    moves.push(move);
  }

Then, you can simply iterate the newly created moves variable.

{moves.map((move, i) => {
        return (
          <p key={i}>
            {i + 1}. {move}
          </p>
        );
      })}

Note: You can use li instead of p tag.

Result:

enter image description here

Working demo at CodeSandbox.

Should be able to do something like:

moves.map((move, i) => {
    return (
        <li key={i}>{i}
            {`move[i].to` + move[i+1] ? `, move[i+1].to` :''}
        </li>
    )
})
Related