'How to show results of a .map in two columns using react

I would like to map an array the result in two columns, alternating which item each element goes in.

So, for const arr = [1, 2, 3, 4, 5, 6]

I would like the result to looks like:

   1 2
   3 4
   5 6

I know I can slice the array, and map over the resulting two smaller ones to get:

   1 4
   2 5
   3 6

But cannot figure out how to get my desired result. Thank you!



Solution 1:[1]

You can render a list of numbers and use the Grid layout in order to create a grid container with 2 columns:

App.js:

export default function App() {
  const numbers = [1, 2, 3, 4, 5, 6]
  
  return <div className="app">{numbers.map((number) => <div>{number}</div>)}</div>
}

style.css:

.app {
  display: grid;
  grid-template-columns: 10px 10px;
}

Demo: https://stackblitz.com/edit/react-sukmzw?file=src%2Fstyle.css

Solution 2:[2]

If you want the output to be displayed like this. Why not simply use CSS? Just run the .map() function as we do normally then apply css to the respective container like so:

// your class name
.container {
  columns: 2 auto
}

FYI, the columns property is a shorthand property for:

  • column-width
  • column-count

Solution 3:[3]

you can use this code

    const arr = [1, 2, 3, 4, 5, 6];
    let firstList = [...arr];
    let secondList = [...arr];
    firstList.splice(0, arr.length / 2);
    secondList.splice(arr.length / 2, arr.length - 1);

Solution 4:[4]

This is how I would do it

 <div style={{display:'flex'}}>
    <div style={{display:'flex',flexDirection:'column'}}>
      {arr.filter( e => e%2 !== 0 ).map( e => <span>{e}</span>)}
    </div>
    <div style={{display:'flex',flexDirection:'column'}}>
       {arr.filter( e => e%2 === 0 ).map( e => <span>{e}</span>)}
    </div>
 </div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Soufiane Boutahlil
Solution 2 Harry
Solution 3 Arash Ghazi
Solution 4 Chakib Salah