1

Having the following array of objects:

const items = [
  {
    description = 'first description'
  },
  {
    description = 'second description'
  },
  {
    description = 'third description'
  },
  {
    description = 'fourth description'
  },
  ...
]

It's easy to represent the descriptions using map:

{
  items.map((item) => (     
    <div>item.description</div>
  ));
}

Which would output the following:

<div>first description</div>
<div>second description</div>
<div>third description</div>
<div>fourth description</div>
...

However I need to add a container for each pair of elements, so the output should be like this:

<div className="container">
  <div>first description</div>
  <div>second description</div>
</div>
<div className="container">
  <div>third description</div>
  <div>fourth description</div>
</div>
...

I did the following solution, but it's complicated to understand and I think there must be a cleaner one:

{
  let result = [];
  let counter = 0;
  items.forEach((item, index) => {
    if (items.length / 2 > index) {
      result[index] = ( 
        <div className="container">
          <div>items[counter]</div>
          <div>items[counter+1]</div>
        </div>
      );
      counter = counter + 2;
    }
  })
}
{result.map((item) => item)}

Any suggestions?

rfc1484
  • 9,441
  • 16
  • 72
  • 123
  • 1
    You could chunk them and `map` them: [Split array into chunks](https://stackoverflow.com/questions/8495687) and [React: Render new row every 4th column](https://stackoverflow.com/questions/42391499) – adiga Apr 28 '21 at 14:03

1 Answers1

2

Here is a cleaner solution for what you want to do:

const items = [
  {
    description: 'first description'
  },
  {
    description: 'second description'
  },
  {
    description: 'third description'
  },
  {
    description: 'fourth description'
  },
];

function pair(arr, number = 2) {
  return arr.reduce(
    (acc, cur, i) =>
      i % number
        ? Object.assign([...acc], {
            [acc.length - 1]: [...acc[acc.length - 1], cur],
          })
        : [...acc, [cur]],
    []
  );
}

function Render() {
  return <React.Fragment>
    {pair(items).map(x => <div className="container">{x.map(y => <div>{y.description}</div>)}</div>)}
  </React.Fragment>;
}

ReactDOM.render(
  <Render />,
  document.getElementById("react")
);
.container {
  border: 1px solid red;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="react"></div>
Guerric P
  • 30,447
  • 6
  • 48
  • 86