Reputation: 11
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!
Upvotes: 1
Views: 3002
Reputation: 2604
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
Upvotes: 1
Reputation: 546
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>
Upvotes: 1
Reputation: 991
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);
Upvotes: 0
Reputation: 812
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:
Upvotes: 0