M
M
Moro Zota2019-02-12 13:23:02
JavaScript
Moro Zota, 2019-02-12 13:23:02

How to split an array into divs in react?

An array comes in: [1,2,3,4,5,6,7]...
It is necessary that the output be like this:

<div>
 <div>1</div>
 <div>2</div>
 <div>3</div>
</div>

<div>
 <div>4</div>
 <div>5</div>
 <div>6</div>
</div>

<div>
 <div>7</div>
</div>

that is, the array elements themselves were wrapped in a div and every 3 elements were also wrapped. I'm trying with reduce but I can't finish it...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2019-02-12
@morozota

Please, here's to you via reduce:

const chunks = [1,2,3,4,5,6,7].reduce((chunks, value, index) => {
  const chunkIndex = Math.floor(index / 3);

  if (!chunks[chunkIndex]) {
    chunks[chunkIndex] = [];
  }

  chunks[chunkIndex].push(value);

  return chunks;
}, []);

return chunks.map((chunk) => (
  <div key={chunk.join(`-`)}>
    {chunk.map((value) => (
      <div key={value}>
        {value}
      </div>
    ))}
  </div>
))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question