search

Home  >  Q&A  >  body text

Using conditions in an array map loop (Next.js)

Final result UI

So I have this data

var arr = [1,2,3,4,5,6,7,8]

I want to check if the array index is a multiple of 5, so every time the loop is at index 0, 5, 10, etc. it will print this html <div class="slide-item"> <div>{data}</div></div> But when it is not at index 0, 5, 10, etc. (meaning it is at 1, 2, 3, 4, 6, 7, 8 etc.), it will print

<div class="slide-item"><div>{data 1}</div><div>{data 2}</div></div><div class="slide-item"><div>{data 3}</div><div>{data 4}</div></div>

So basically the final result UI is like the attached picture.

My first attempt was like this

{arr.map((res, index) => {return ({index % 5 === 0 ? (<div className="slide-item"><div>{res}</div></div>): (<div class="slide-item"><div>{data 1}</div><div>{data 2}</div></div>)}

I'm not quite sure how to do this, if anyone can help it would be greatly appreciated!

P粉034571623P粉034571623275 days ago442

reply all(1)I'll reply

  • P粉107991030

    P粉1079910302024-03-28 00:03:22

    I think you need to check the condition based on res since the index always starts from 0

    Try this

    {
        arr.map((res, index) => {
            return ( res % 5 === 0 
                ? <div className="slide-item"><div>{res}</div></div>
                : <div>
                     <div class="slide-item"><div>{data 1}</div>
                     <div>{data 2}</div></div>
                  </div>
             )       
         })
    }

    reply
    0
  • Cancelreply