I have an array of elements. What I want is to add the elements to a div but strategically. First, add class .wrapperItems then add only 5 elements from the array then if there are more elements left in the array create a new .wrapperItems div and append the remaining array elements. Loop until all the array elements have been appended. How can I achieve this? Thanks in advance.
Take a look at my HTML code below to get an idea of what I want the structure to look like.
*The solution must work with any array length!
let myArray = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9']
$('.wrapper .wrapperItems').html('')
myArray.forEach((elm) => {
//add only 5 "itemCon" then create new ".wrapperItems"
$('.wrapper .wrapperItems').append(`<div class="itemCon"><p>${elm}</p></div>`)
})
.wrapper {
display: flex;
flex-direction: column;
width: 100%;
height: fit-content;
background-color: gold;
}
.wrapperItems {
display: flex;
flex-direction: row;
justify-content: center;
width: 100%;
height: fit-content;
background-color: coral;
}
.itemCon {
display: flex;
width: 15%;
height: 7vh;
background-color: pink;
}
.itemCon p {
margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="wrapperItems">
<div class="itemCon">
<p>test</p>
</div>
<div class="itemCon">
<p>test</p>
</div>
<div class="itemCon">
<p>test</p>
</div>
<div class="itemCon">
<p>test</p>
</div>
<div class="itemCon">
<p>test</p>
</div>
</div>
<div class="wrapperItems">
<div class="itemCon">
<p>test</p>
</div>
<div class="itemCon">
<p>test</p>
</div>
<div class="itemCon">
<p>test</p>
</div>
<div class="itemCon">
<p>test</p>
</div>
<div class="itemCon">
<p>test</p>
</div>
</div>
</div>
This is really a question about how to chunk an array into an array of arrays.
This can be done by mapping and grouping.
let myArray = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9','test10','test11'];
const result = Object.values(
myArray.map( (x,i) => ({grp:Math.floor(i/5),val:x}))
.reduce((acc,i) => {
acc[i.grp] ||= [];
acc[i.grp].push(i.val);
return acc;
},{})
);
console.log(result);
At that point, its just a matter of forEach over the outer array where each element will be an array of (up to) 5 items
let myArray = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9']
const result = Object.values(
myArray.map( (x,i) => ({grp:Math.floor(i/5),val:x}))
.reduce((acc,i) => {
acc[i.grp] ||= [];
acc[i.grp].push(i.val);
return acc;
},{})
);
result.forEach((elm) => {
//add only 5 "itemCon" then create new ".wrapperItems"
const $wrapperItems = $("<div>").addClass("wrapperItems");
elm.forEach(item => {
$wrapperItems.append(`<div class="itemCon"><p>${item}</p></div>`)
});
$(".wrapper").append($wrapperItems);
})
.wrapper {
display: flex;
flex-direction: column;
width: 100%;
height: fit-content;
background-color: gold;
}
.wrapperItems {
display: flex;
flex-direction: row;
justify-content: center;
width: 100%;
height: fit-content;
background-color: coral;
}
.itemCon {
display: flex;
width: 15%;
height: 7vh;
background-color: pink;
}
.itemCon p {
margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
</div>
First, break down your array into chunks of 5.
const chunkSize = 5;
function chunkify(arr, size) {
for (let i = 0; i < arr.length; i++) {
let toSplice = arr.splice(i, size);
arr.unshift(toSplice);
}
return arr.reverse();
}
Then iterate over the chunked array to get the desired output.
const myArray = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9']
const chunkedArray = chunkify(myArray, chunkSize);
const $parentEl = $('.wrapper');
chunkedArray.forEach((arr) => {
const $wrapper = $('<div/>', { 'class': 'wrapperItems' });
arr.forEach(item => {
const $itemCon = $('<div/>', { 'class': 'itemCon' });
const $p = $('<p/>', { text: item });
$itemCon.append($p);
$wrapper.append($itemCon);
});
$parentEl.append($wrapper);
});
This is a solution that loops through the items in the array and creates a new container for the newly created corresponding divs every time each "slice" got completed.
Consider that you just have to visit each node of your input data and behave with an action accordingly so there's no need to create added data structure just for the sake of approaching the grouping ex-post when choosing the action to perform.
I can't think of a more readable and more efficient approach than this:
let items = [
'test1',
'test2',
'test3',
'test4',
'test5',
'test6',
'test7',
'test8',
'test9'
];
const slice = 5;
const target = $('#wrapper');
let currentGroup;
let itemCounter = 0;
for(const item of items){
if (itemCounter++ % slice == 0) {
currentGroup = $('<div></div>').addClass("wrapperItems");
$(target).append( currentGroup );
}
$(currentGroup).append( $('<div></div>').addClass("itemCon") );
}
.wrapper {
display: flex;
flex-direction: column;
width: 100%;
height: fit-content;
background-color: gold;
}
.wrapperItems {
display: flex;
flex-direction: row;
justify-content: center;
width: 100%;
height: fit-content;
background-color: coral;
border: solid blue 1px;
}
.itemCon {
display: flex;
width: 15%;
height: 7vh;
background-color: pink;
border: solid red 1px;
}
.itemCon p {
margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
</div>