Improve code of groupBy() & sortBy()