ported groupByUntil function.