Sheildboy
Sheildboy

Reputation: 87

Creating a submenu in React js using an array of elements

Is there any way to create the following structure without dividing the array into two and mapping over it

arrayList=[Jeans, Jackets, Pants, Fragrance, Sunglasses, Health Products]
<div className='Flexbox'>
//arrayList1.map](//arrayList1.map)(x=>return(<li>x</li>))

<div className='first sublist'>

    <li>Jean</li>

    <li>Jackets</li>

    <li>Pants</li>

</div>

<div className='first sublist'>

//arrayList2.map](//arrayList2.map)(x=>return(<li>x</li>))

    <li>Fragrance</li>

    <li>Sunglasses</li>

    <li>Health</li>

</div>

Upvotes: -1

Views: 385

Answers (2)

prasanth
prasanth

Reputation: 22490

Try to split first two half using Array#reduce. Then apply the map for parent then apply map for li

const arrayList = ['Jeans', 'Jackets', 'Pants', 'Fragrance', 'Sunglasses', 'Health Products'];

let res = arrayList.reduce((acc,curr,ind)=>{
  if(ind%3 == 0){ // splitting into two array
   acc[ind/3] = [];
  }
  acc[acc.length-1].push(curr) // push the value to last created array
  return acc
},[]).map((item)=>(
   <div className="first sublist"> //div wrap
      {item.map(text=>( //for inner text
        <li>text</li>
      ))}
   </div>
))

Upvotes: 1

k-wasilewski
k-wasilewski

Reputation: 4623

I'm not sure, are you asking for something like this?

{ arrayList.map((item, index) => {
    return (
        (index <= arrayList.length / 2) ?
            <li> {item} </li>
            :
            null
    );
}}

Upvotes: -1

Related Questions