written groupBy function