I just implemented my idea step by step and I think it totally fullfills your objective.
//DESCRIPTION:Group by horizontal extent
// A Jongware Script 26-Dec-2011
// grab selection
elements = app.selection;
// sort on tops
elements.sort (function(x,y)
{
return x.geometricBounds[0] - y.geometricBounds[0];
}
);
// put in simple buckets, saving bottom and contains:array of elements
buckets = [ ];
for (i=0; i<elements.length; i++)
{
e_top = elements.geometricBounds[0];
e_bottom = elements.geometricBounds[2];
b = 0;
while (b < buckets.length && (e_top > buckets.bottom) )
b++;
// not in an available bucket? add one!
if (b == buckets.length)
buckets.push ( {bottom:e_bottom, contains:[ elements ] } );
else
{
// put in bucket
buckets.contains.push ( elements );
// update range
if (e_bottom > buckets.bottom)
buckets.bottom = e_bottom;
}
}
// add label for debugging purposes:
for (i=0; i<buckets.length; i++)
{
app.activeDocument.textFrames.add ({geometricBounds:[ buckets.contains[0].geometricBounds[0], 0, buckets.bottom, 20 ], contents:String(i)+" => "+String(buckets.contains.length) } );
}
// deselect all
app.select(null);
// convert to groups and re-select
for (i=0; i<buckets.length; i++)
{
if (buckets.contains.length > 1)
app.select ([app.activeDocument.groups.add (buckets.contains)], SelectionOptions.ADD_TO);
else
app.select(buckets.contains, SelectionOptions.ADD_TO);
}