The issue at hand is not related to JavaScript but can be easily resolved with a crash course in CSS. The confusion seems to stem from the focus on the "row". It's important to approach this problem by creating a grid container that specifies each row can hold a maximum of 3 items. For instance, if you insert 7 children into the container, you will have 2 complete rows and 1 partially filled row. Let me illustrate.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 columns */
}
The use of 1fr denotes that each item should have equal width. The number 3 before it indicates the quantity of items in the repeat() function.
Example
Following your example closely, I've provided several demonstrations. In this second example, I show how you can identify every "row", which consists of every 3n elements, and set its column width using CSS.
/* If the last row has only one item, that item should span three columns. */
.grid-container > :nth-child(3n+1):last-child {
background: red;
grid-column: span 3;
}
<button onclick="addItem()">+</button>
<button onclick="removeItem()">-</button>
<div class="grid-container">
<div class="grid-item">Item 1</div>
<div class="grid-item">Item 2</div>
<div class="grid-item">Item 3</div>
<div class="grid-item">Item 4</div>
<div class="grid-item">Item 5</div>
<div class="grid-item">Item 6</div>
<div class="grid-item">Item 7</div>
</div>
Example #3
In addition to the previous examples, I implemented what should occur when there are 2 columns left in the last row. This scenario presents a challenge as fractional values cannot be specified in grids. Hence, I adjusted the total column width to accommodate the situation—each column being 2 units wide allows us to fit 3 columns within the grid. Therefore, the width of an item in the last row is determined by the number of items present: either 6 or 3 columns wide.
.grid-container {
display: grid;
grid-template-columns: repeat(6, 1fr); /* 6 columns */
}
...
<button onclick="addItem()">+</button>
<button onclick="removeItem()">-</button>
<div class="grid-container">
<div class="grid-item">Item 1</div>
<div class="grid-item">Item 2</div>
<div class="grid-item">Item 3</div>
<div class="grid-item">Item 4</div>
</div>
Note: The inclusion of JavaScript functions and buttons was purely for demonstration purposes; my solution primarily relies on CSS for efficiency. There's no need to worry about array changes or looping tasks.
By solely utilizing CSS in my solution, modifications to the list array are unnecessary, and there's no requirement for running loops.