Unknown number of elements but I know how many columns I want - fill data from top to bottom

Viewed 23

I am fetching unknown number of data elements from the DB. Each element will be displayed inside some <div> with style.

I know that I want to show 4 columns, but fill the data from top to bottom.

so if I get an array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Display it like so:

1  4  7  10

2  5  8  11

3  6  9

Is there convenient way with bootstrap or I will have to calculate the number of elements first then while iterating them I assign new row/column?

1 Answers

The best solution I could come up with involves calculating the elements per column by dividing total elements count with total columns count and applying Math.ceil on the result. Like you mentioned in your question, you then have to simply iterate through the number of columns and the number of elements per column and append each element to the proper column.

HTML:

<div class="row" id="container">
    <div class="col-3">
    
    </div>
    <div class="col-3">
    
    </div>
    <div class="col-3">
    
    </div>
    <div class="col-3">
    
    </div>
</div>

JavaScript:

window.onload = function() {
    var container = document.getElementById("container");

    var columns = container.children.length;
    var elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
    
    var elementsPerColumn = Math.ceil(elements.length / columns);
  
    var index = 0;
    
    for (var i = 0; i < columns; i++) { 
        var column = container.children.item(i);
  
        for (var j = 0; j < elementsPerColumn; j++) {    
            var item = elements[index];
                        
            if (item != undefined)
            {
                var divElement = document.createElement('div');
                divElement.classList.add('my-div');
                divElement.innerHTML = item;
                
                column.appendChild(divElement);
            }
            
            index++;
        }  
    }
};

https://jsfiddle.net/bp145k9u/2/

(Posting my solution as answer in case someone finds it useful.)

Related