Home > OS >  How do I load arrays to map into columns with multiple rows?
How do I load arrays to map into columns with multiple rows?

Time:10-11

I want to have an array, something like this:

let thisArray = [1,2,3,4,5,6,7,8];

and I want to be able to map the array into a 2x4 column/row.

<div className='numberRow'>
    <div className='numberCol'>1</div>
    <div className='numberCol'>2</div>
</div>
<div className='numberRow'>
    <div className='numberCol'>3</div>
    <div className='numberCol'>4</div>
</div>
<div className='numberRow'>
    <div className='numberCol'>5</div>
    <div className='numberCol'>6</div>
</div>
<div className='numberRow'>
    <div className='numberCol'>7</div>
    <div className='numberCol'>8</div>
</div>

is it possible to use map() and start a new row?

CodePudding user response:

You can split the array into chunks of 2 by creating a new array and using Array.push and Array.splice, then map through each item and construct the HTML:

let thisArray = [1, 2, 3, 4, 5, 6, 7, 8];

let split = []

while (thisArray.length > 0) {
  split.push(thisArray.splice(0, 2));
}

const HTML = split.map(e => `<div className='numberRow'>
    <div className='numberCol'>${e[0]}</div>
    <div className='numberCol'>${e[1]}</div>
</div>`).join('')

document.write(HTML)
[className=numberRow]{background-color:yellow;padding:10px}[className=numberCol]{background-color:lightgrey}

CodePudding user response:

You can use the Array#reduce() method to create the desired array of data, then you can use the Array#map() method to create the HTML as in the following demo:

let thisArray = [1,2,3,4,5,6,7,8];
let twoCol = thisArray.reduce((acc,cur,i,a) => 2*i < a.length ? acc.concat([a.slice(2*i,2*i 2)]) : acc,[]);
console.log( twoCol );

let table = twoCol.map(([c1,c2]) => `<div className='numberRow'>
    <div className='numberCol'>${c1}</div>
    <div className='numberCol'>${c2}</div>
</div>`)
.join('');
console.log( table );

  • Related