Refactor and add unit test for groupedResults