-1

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>
3
  • 2
    Why you don't want dividing the array and mapping over it? Commented Jan 17, 2021 at 13:31
  • just wanted to know if there is any way to solve this using just one loop. Is using too loops efficient? Commented Jan 17, 2021 at 13:57
  • How do you define loop? If the array should always be split to two part, and you know how to split, you can use slice to split the array to two part and map each other, And spliting may be not a loop? Commented Jan 17, 2021 at 14:01

2 Answers 2

1

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>
))
Sign up to request clarification or add additional context in comments.

Comments

-1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.