added imperative version for groupBy