0

I'm wondering if there's a good way I could map data from an array where I can display the items in groups of 2. An example would be displaying multiple divs from mapping an array like this:

Array:

const sampleArray = [object1, object2, object3, object4]

Desired output:

<div> 
  <object1 />  
  <object2 /> 
</div>

//next div container will contain object3 and object4
Patorikku
  • 61
  • 8
  • 1
    Not with just `map()` - it's for 1:1 conversion, not many:less. You're supposed to [chunk the array](https://stackoverflow.com/questions/8495687/split-array-into-chunks) for that. – VLAZ Dec 04 '21 at 08:37
  • You CAN map into divs – mplungjan Dec 04 '21 at 08:40
  • Something like `const html = sampleArray.map((item,i) => i%2 ? \`
    ${sampleArray[i-1]}${sampleArray[i]}
    \` : '').join("")`
    – mplungjan Dec 04 '21 at 08:43
  • @mplungjan yes, you can make `.map()` do many things which I'd argue is not meant to do. I do not think it should be (mis-)used for that, though. It's a very "when all you have is a hammer" way of problem solving. – VLAZ Dec 04 '21 at 08:59
  • My map example is on the borderline, but op is processing all the elements in the array – mplungjan Dec 04 '21 at 09:03
  • Yeah I agree with @VLAZ, I made something similar using `.join`, but I found it very messy and confusing. – Patorikku Dec 04 '21 at 09:04

0 Answers0