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?