I have this array of HTML items that I want them to be looped and inserted into group of HTMLs:
const htmlToBeLooped = [
`<div>
<span>ID: 2</span>
<span>ID: name2</span>
</div>`,
`<div>
<span>ID: 2</span>
<span>ID: name2</span>
</div>`,
`<div>
<span>ID: 3</span>
<span>ID: name3</span>
</div>`,
`<div>
<span>ID: 4</span>
<span>ID: name4</span>
</div>`,
`<div>
<span>ID: 5</span>
<span>ID: name5</span>
</div>`,
`<div>
<span>ID: 6</span>
<span>ID: name6</span>
</div>`,
`<div>
<span>ID: 7</span>
<span>ID: name7</span>
</div>`,
`<div>
<span>ID: 8</span>
<span>ID: name8</span>
</div>`,
`<div>
<span>ID: 9</span>
<span>ID: name9</span>
</div>`,
`<div>
<span>ID: 10</span>
<span>ID: name10</span>
</div>`
];
I want it to be converted to:
<div id="container-1">
<div>
<span>ID: 1</span>
<span>ID: name1</span>
</div>
<div>
<span>ID: 2</span>
<span>ID: name2</span>
</div>
<div>
<span>ID: 3</span>
<span>ID: name3</span>
</div>
</div>
<div id="container-2">
<div>
<span>ID: 4</span>
<span>ID: name4</span>
</div>
<div>
<span>ID: 5</span>
<span>ID: name5</span>
</div>
<div>
<span>ID: 6</span>
<span>ID: name6</span>
</div>
</div>
<div id="container-3">
<div>
<span>ID: 7</span>
<span>ID: name7</span>
</div>
<div>
<span>ID: 8</span>
<span>ID: name8</span>
</div>
<div>
<span>ID: 9</span>
<span>ID: name9</span>
</div>
</div>
<div id="container-4">
<div>
<span>ID: 10</span>
<span>ID: name10</span>
</div>
</div>
Given that there should be a maximum of 3(this is varied) items in each group.
After researching in StackOverflow I came up with this but it failed:
const loopLimit = 3;
const sectionsToBeShown = Math.ceil(htmlToBeLooped.length / loopLimit);
let html = '';
for(let i = 0; i < sectionsToBeShown; i++) {
html += `<div id='container-${i + 1}'>`
for(var x = 0; x < htmlToBeLooped.length; x += loopLimit){
const limitedhtml = htmlToBeLooped.slice(x, x + loopLimit);
for(var y = 0; y < limitedhtml.length; y++){
html+= limitedhtml[i];
}
}
html += `</div>`
}
document.write(html)
Would really appreciate someone's help as I've been stuck on this trying different approaches for a couple of hours now.