looking at the related questions on the side I found the answer (more or less) written in another language. Trick is to first calculate the number of rows and columns your grid needs to have (based on the length of your array), then to do a loop inside a loop, where the first loop iterates your rows and the second your columns.
here's the javascript translation of that other answer
function popUp(){
// calculate number of rows and columns
var cols = Math.ceil(Math.sqrt(queue.length));
var rows = Math.ceil(queue.length/cols);
// calculate width and height based on number of cols && rows
var W = screen.width / cols;
var H = screen.height / rows;
var item = 0; //item of the queue array
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
window.open(queue[item],item,'width='+W+',height='+H+',toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left='+W*j+',top='+H*i+'');
item++; //add 1 to item
if(item >= queue.length) { break } //break out of loop once item reaches length of queue
}
}
}
this loop would always create a perfect grid, which might not always be what you want, if you've got an odd number of items the last row should be missing a few cells, but this loop-ina-loop would create empty pop ups to finish off the grid, this is why we add that last line to break out of the loop once items >= queue.length (i.e. once you've reached the end of your queue)
UPDATE:
here's looping in reverse (little easier to read up here than in the comment)
for(i=rows-1; i>=0; i--) {
for(j=cols-1; j>=0; j--) {
//pop up code
}
}